如何使用 C# 将点击侦听器分配给在运行时在 Unity 中创建的游戏对象?
How do I assign an on click listener to a game object that is created at runtime in Unity using C#?
我创建了一个四边形。我将此脚本分配给包含游戏对象数组的四边形:
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;
}
}
}
}
我克隆了这些游戏对象,使它们出现在这样的网格上:
当用户点击一个对象时,它应该会消失。我所做的是将这个脚本放在我的游戏对象数组中的每个元素上:
public class ShapeBehavior : MonoBehaviour {
void Update(){
if(Input.GetMouseButtonDown(0)){
Destroy(this.gameObject);
}
}
}
但是当我点击一个对象来销毁它时,该对象的每个克隆都将被销毁。我只想销毁特定的克隆,而不是全部。我该怎么做?
问题出在您的 Input 调用上,当您单击鼠标按钮时,"Input.GetMouseButtonDown(0)" 在每个脚本中都是正确的,无论鼠标的位置如何。将任何类型的碰撞器附加到 gameObject 并设置它并使用 OnMouseDown() 方法放置脚本,在此处查看更多信息:http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
您也可以使用光线投射,但这是解决此问题的更高级方法。
同时将 this.gameObject 替换为 gameObject。
我创建了一个四边形。我将此脚本分配给包含游戏对象数组的四边形:
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;
}
}
}
}
我克隆了这些游戏对象,使它们出现在这样的网格上:
当用户点击一个对象时,它应该会消失。我所做的是将这个脚本放在我的游戏对象数组中的每个元素上:
public class ShapeBehavior : MonoBehaviour {
void Update(){
if(Input.GetMouseButtonDown(0)){
Destroy(this.gameObject);
}
}
}
但是当我点击一个对象来销毁它时,该对象的每个克隆都将被销毁。我只想销毁特定的克隆,而不是全部。我该怎么做?
问题出在您的 Input 调用上,当您单击鼠标按钮时,"Input.GetMouseButtonDown(0)" 在每个脚本中都是正确的,无论鼠标的位置如何。将任何类型的碰撞器附加到 gameObject 并设置它并使用 OnMouseDown() 方法放置脚本,在此处查看更多信息:http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
您也可以使用光线投射,但这是解决此问题的更高级方法。
同时将 this.gameObject 替换为 gameObject。