When destroying instantiated clone it will destroy all spawned clones.need help

Im making simple kill ants game to practise some C#. Im spawning objects(ant) randomly and destroy them when i click. But now when i leave more than 1 ant in screen click will destroy all.

I just want that 1 gameobject(ant) will get destroyed.

click and destroy script is attached to object(ant) what i am spawnin with gamecontroller script

    void FixedUpdate ()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
           
            if(hit.collider != null)
            {
                Destroy (gameObject);
            }
        }
    }
}

spawn script

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
   
    public Camera cam;
    public GameObject ant;

    private float maxWidth;
    private float maxHeight;
   
    void Start ()
    {
        if (cam == null)
        {
            cam = Camera.main;
        }
        Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
        Vector3 target_xy = cam.ScreenToWorldPoint (upperCorner);
        maxWidth = target_xy.x;
        maxHeight = target_xy.y;
        StartCoroutine (Spawn ());
    }
    IEnumerator Spawn ()
    {
        yield return new WaitForSeconds (2.0f);
        while (true)
        {
            Vector3 spawnPosition = new Vector3 (Random.Range (-maxWidth, maxWidth), Random.Range (-maxHeight, maxHeight), 0.0f);
            Quaternion spawnRotation = Quaternion.identity;
            Instantiate (ant, spawnPosition, spawnRotation);
            yield return new WaitForSeconds (Random.Range(1.0f, 2.0f));
        }
    }
}

need some help

You are not checking if the raycast hit is this ants collider, and the script executes on all ants at the same time.
A simple ‘fix’ would be on line 9
if(hit.collider != null)
should be more like
if(hit.collider == myCollider)
Where myCollider is the collider of the ant that the script is on

1 Like

but hit.collider is the ant collider? i dont have collider on the the cursor with im targeting the ant. 2 colliders cant work?

Ok i got it
if(hit.collider == collider2D)…works now.
thanks

The same script on every ant executes, and each one create the same ray when you click, so each script is testing the same hit.collider, and it’s not null in each execution

1 Like