Search code examples
c#unity-game-enginespritegameobject

Destroying game object


I have created a simple 2D touch game in Unity and I have spikes spawning at the top of the scene every 3 seconds and when the spikes fall the player will tap the spikes before they hit the characters below, however, when I test the game, when I tap the spike (game object) it destroys all of the spikes (game objects) in the scene. Here is the code:

public GameObject spike;
public float spawnTime1 = 1f;

// Use this for initialization
void Start () {
    InvokeRepeating ("SpawnSpike", spawnTime1, spawnTime1);

}

// Update is called once per frame
void Update () {
    for (var i = 0; i < Input.touchCount; ++i) {
        if (Input.GetTouch(i).phase == TouchPhase.Began) {
            Destroy (gameObject);
        }
    }
}

void SpawnSpike () {

    var newSpike = GameObject.Instantiate (spike); 
    newSpike.transform.position = new Vector3 (Random.Range(-3, 3), 11f, 0f);

Solution

  • It looks like you're destroying this game-manager-like script itself when you run

    void Update () {
        for (var i = 0; i < Input.touchCount; ++i) {
            if (Input.GetTouch(i).phase == TouchPhase.Began) {
                Destroy (gameObject);
            }
        }
    }
    

    The line Destroy (gameObject); is destroying its own game-object, which I'm guessing is parented to the spikes that are instantiated(?); hence destroying all the spikes at once.

    I suggest using raycasts to find out if any spike is tapped on and/or which spike is tapped on, and then destroying only the game-object of that spike. Here's a good reference. I also suggest looking for tutorials regarding the same if you're still finding it hard to understand.

    I hope that helps!

    UPDATE:

    Here's some sample code to get you going:

        if (Input.GetTouch(i).phase == TouchPhase.Began) {
            Vector3 pos = Camera.main.ScreenToWorldPoint (Input.GetTouch(i).position);
            RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
            if (hit != null && hit.gameObject.CompareTag("spike") && hit.collider != null) {
                Debug.Log ("I'm tapping "+hit.gameObject.name);
                Destroy(hit.gameObject);
            }
        }
    

    This specific code would require that your spike prefab (template) has the tag "spike". I also suggest you place this code in some kind of a global "game-manager" script's Update() (rather than in the Spike script), so that you don't over-process the touches.