如何将单击侦听器分配给在运行时使用C#在Unity中创建的游戏对象?

如何将单击侦听器分配给在运行时使用C#在Unity中创建的游戏对象?,c#,unity3d,scripting,C#,Unity3d,Scripting,我创建了一个四边形。我将此脚本分配给包含游戏对象数组的四边形: public class ShapeGrid : MonoBehaviour { public GameObject[] shapes; void Start(){ GameObject[,] shapeGrid = new GameObject[3,3]; StartCoroutine(UpdateGrid()); } IEnumerator UpdateGrid

我创建了一个四边形。我将此脚本分配给包含游戏对象数组的四边形:

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.GetMouseButtonDown(0)”在您单击鼠标上的按钮时在每个脚本中都是正确的,无论鼠标的位置如何。将任何类型的碰撞器连接到gameObject并进行设置,然后使用OnMouseDown()方法放置脚本,请查看此处以了解更多信息:

您也可以使用光线投射,但这是解决此问题的更高级方法


还可以用gameObject替换this.gameObject。

成功了!非常感谢。但这导致了另一个错误。MissingReferenceException:类型为“GameObject”的对象已被销毁,但您仍在尝试访问它。你的脚本应该检查它是否为空或者你不应该破坏这个对象。你到底是从哪个脚本得到的?我分配给四元组的脚本。它来自这一行:gameobjectshape=实例化(shapes[shapeId]);没有关系。我在运行时将脚本添加到克隆对象中,而不是在运行时之前使用此代码将它们添加到原始对象中,从而解决了这个问题。shape.AddComponent();但问题是,有时OnMouseDown()方法执行,有时不执行。我不知道它什么时候会,什么时候不会。在运行时之前,运行时之后检查脚本是否成功附加到inspector中,也检查碰撞器。