![](/img/trans.png)
[英]UNITY C# - How can I save a Game Object, that has been instantiated in a runtime, in a runtime?
[英]How do I assign an on click listener to a game object that is created at runtime in Unity using C#?
我创建了一个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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.