創建新的腳本我怎樣才能點擊並用鼠標拖動一個gameobject?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseDrag : MonoBehaviour
{
float distance = 10;
void OnMouseDrag()
{
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = objPosition;
}
}
然後在啓動功能的另一個劇本我創建4個立方體,並添加mouseDrag每個立方體。但是,運行並單擊並拖動時不會發生任何事情。我沒有收到任何錯誤或例外。
void Start()
{
lp = gameObjectToRaise.transform.localPosition;
ls = gameObjectToRaise.transform.localScale;
List<GameObject> cubes = new List<GameObject>();
GameObject cube = Cube.CreatePrimitive(Cube.CubePivotPoint.UPLEFT);
GameObject cube1 = Cube.CreatePrimitive(Cube.CubePivotPoint.UPRIGHT);
GameObject cube2 = Cube.CreatePrimitive(Cube.CubePivotPoint.BACKUP);
GameObject cube3 = Cube.CreatePrimitive(Cube.CubePivotPoint.UPRIGHT);
cubes.Add(cube);
cubes.Add(cube1);
cubes.Add(cube2);
cubes.Add(cube3);
cube.GetComponentInChildren<Renderer>().material.color = Color.blue;
cube1.GetComponentInChildren<Renderer>().material.color = Color.red;
cube2.GetComponentInChildren<Renderer>().material.color = Color.green;
cube3.GetComponentInChildren<Renderer>().material.color = Color.yellow;
cube.transform.position = new Vector3(lp.x, lp.y, lp.z - 0.5f);
cube1.transform.position = new Vector3(lp.x, lp.y, lp.z);
cube2.transform.position = new Vector3(lp.x, lp.y, lp.z + 5);
cube3.transform.position = new Vector3(lp.x + 5, lp.y, lp.z);
cube1.transform.Rotate(0, 90, 0);
cube3.transform.Rotate(0, 90, 0);
StartCoroutine(scaleCube(cube.transform));
StartCoroutine(scaleCube(cube1.transform));
StartCoroutine(scaleCube(cube2.transform));
StartCoroutine(scaleCube(cube3.transform));
foreach (GameObject go in cubes)
{
go.AddComponent<mouseDrag>();
}
}
IEnumerator scaleCube(Transform trans)
{
while (raiseAmount < raiseTotal)
{
raiseAmount += 1f;
trans.localScale += new Vector3(speed * Time.deltaTime, speed * Time.deltaTime, 0);
yield return null;
}
}
}
什麼是您的相機模式?透視還是正視? – Programmer
@Programmer我剛剛嘗試了一個單獨的多維數據集gameobject,我添加了它來測試它,它工作正常。但是,當我使用多維數據集使用CUBE類助手它不工作。也許問題是它將腳本附加到parentObject「CubeHolder」而不是創建的多維數據集?當我運行遊戲時,我在4個「CubeHolder」的每個下面看到一個智利立方體,但腳本附加到「CubeHolder」,而不是4個「CubeHolder」中的每個的子立方體。 –