Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在unity中通过运行时拖放创建对象_C#_User Interface_Unity3d_Drag And Drop - Fatal编程技术网

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){}
实现该逻辑