通过在运行时以统一的方式拖放来创建对象

时间:2015-07-02 06:52:34

标签: c# user-interface unity3d drag-and-drop

我必须通过在运行时拖动按钮来创建对象。我搜索了很多,但我找不到解决方案。

我通过使用以下示例代码单击按钮来创建对象。但我必须拖放。

我的代码是:

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);

}
}

1 个答案:

答案 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);
    }
}