C# 在unity中通过运行时拖放创建对象
我必须在运行时拖动按钮来创建对象。我找了很多,但还是找不到解决办法 我使用下面的示例代码通过单击按钮创建对象。但我必须拖拽 我的代码是:C# 在unity中通过运行时拖放创建对象,c#,user-interface,unity3d,drag-and-drop,C#,User Interface,Unity3d,Drag And Drop,我必须在运行时拖动按钮来创建对象。我找了很多,但还是找不到解决办法 我使用下面的示例代码通过单击按钮创建对象。但我必须拖拽 我的代码是: using UnityEngine; using System.Collections; public class CreateSphere : MonoBehaviour { public void OnClick() { GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.
using UnityEngine;
using System.Collections;
public class CreateSphere : MonoBehaviour {
public void OnClick()
{
GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
sphere.transform.localScale = new Vector3(3.0f, 3.0f, 1.0f) ;
//transform.Translate(0, 0, Time.deltaTime);
sphere.transform.position = new Vector3 (4, 0, 0);
}
}
OnClick
不是拖动,只是单击一下。要拖动,需要有拖动处理程序
using UnityEngine;
using UnityEngine.GUI;
using UnityEngine.EventSystems;
using System.Collections;
public class CreateSphere : MonoBehaviour, IBeginDragHandler, IDragHandler {
GameObject sphere;
public void OnBeginDrag(PointerEventData data)
{
// Begin dragging logic goes here
sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
}
public void OnDrag(PointerEventData data)
{
// Dragging logic goes here
sphere.transform.localScale = new Vector3(3.0f, 3.0f, 1.0f) ;
//transform.Translate(0, 0, Time.deltaTime);
sphere.transform.position = new Vector3 (4, 0, 0);
}
}
你需要一种方法来跟踪鼠标在世界上的位置,并不断更新新的
游戏对象的位置以匹配,直到你放开鼠标。类似于Camera.ScreenToWorldPoint
和Input.mousePosition
的功能会有所帮助。当我稍微拖动按钮时,对象将在点0,0,0处创建。但是我必须在释放鼠标按钮的地方创建对象。如何做到这一点?实现IEndDragHandler
接口,然后使用方法public void OnEndDrag(PointerEventData data){}
实现该逻辑