How to assign a click listener to a game object that is created at runtime in Unity using C #?

I created a quad. I assigned this script to Quad, which contains an array of game objects:

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;
            }
        }
    }
}

I cloned these game objects so that they appear in the grid as follows:

enter image description here

When the user clicks on an object, it should disappear. I made this script for every element in my Game Objects array:

public class ShapeBehavior : MonoBehaviour {
    void Update(){
        if(Input.GetMouseButtonDown(0)){
            Destroy(this.gameObject);
        }
    }
}

But what happens when I click on an object to destroy it, every clown of that object will be destroyed. I want to destroy only a specific clone, not all. How to do it?

+4
source share
1 answer

, "Input.GetMouseButtonDown(0)" script, , . gameObject script OnMouseDown(), : http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

raycasting, .

this.gameObject gameObject.

0

Source: https://habr.com/ru/post/1612208/


All Articles