如何使用C#为在Unity运行时创建的游戏对象分配一个on click侦听
发布时间:2020-12-15 20:56:17 所属栏目:百科 来源:网络整理
导读:我创建了一个Quad.我将此脚本分配给包含游戏对象数组的Quad: public class ShapeGrid : MonoBehaviour { public GameObject[] shapes; void Start(){ GameObject[,] shapeGrid = new GameObject[3,3]; StartCoroutine(UpdateGrid()); } IEnumerator UpdateG
我创建了一个Quad.我将此脚本分配给包含游戏对象数组的Quad:
public class ShapeGrid : MonoBehaviour { public GameObject[] shapes; void Start(){ GameObject[,] shapeGrid = new GameObject[3,3]; StartCoroutine(UpdateGrid()); } IEnumerator UpdateGrid(){ while (true) { SetGrid (); yield return new WaitForSeconds(2); } } void SetGrid(){ int col = 3,row = 3; for (int y = 0; y < row; y++) { for (int x = 0; x < col; x++) { int shapeId = (int)Random.Range (0,4.9999f); GameObject shape = Instantiate (shapes[shapeId]); Vector3 pos = shapes [shapeId].transform.position; pos.x = (float)x*3; pos.y = (float)y*3; shapes [shapeId].transform.position = pos; } } } } 我克隆了那些游戏对象,以便它们出现在这样的网格上: 当用户单击一个对象时,它应该消失.我所做的是将此脚本放在我的Game Objects数组中的每个元素上: public class ShapeBehavior : MonoBehaviour { void Update(){ if(Input.GetMouseButtonDown(0)){ Destroy(this.gameObject); } } } 但是当我点击一个对象来销毁它时,会破坏该对象的每个克隆.我只希望销毁特定的克隆,而不是一切.我怎么做? 解决方法
问题在于您的Input调用,当您单击鼠标上的按钮时,无论鼠标的位置如何,每个脚本中的“Input.GetMouseButtonDown(0)”都为true.将任何类型的对撞机附加到gameObject并进行设置并使用OnMouseDown()方法放置脚本,请在此处查看更多信息:
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
您也可以使用光线投射,但这是解决此问题的更高级方法. 也可以用gameObject替换this.gameObject. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |