Destroy a specific instantiated clone?

Hi!

The player in my game can walk around in the world and with a mouse click place objects in the world. The objects placed are instantiated from a prefab and are called “Brick(Clone)” in the hierarchy. The code for the instantiate below.


var cube : Transform;

function setcube () {
	// Get aim position and round to nearest grid space
	var aimx = Mathf.RoundToInt(transform.position.x + 0);
	var aimy = Mathf.RoundToInt(transform.position.y + 0);
	var aimz = Mathf.RoundToInt(transform.position.z + 0);
    
    // Place cube
    var cube = Instantiate(cube, Vector3 (aimx, aimy, aimz), Quaternion.identity);
}

It seems to work pretty ok. But then I want the player to be able to remove an object with a right click. I’ve been at this for a few days but can’t think of a way to to it. How do I know which specific instance of a clone to destroy? Destroy(gameObject) just destroys the first created (there could be thousands). I’ve messed around with OnCollisionEnter functions on the cube to detect when a user interacts with them but it won’t work. The clones don’t seem to have IDs or any way of getting to a specific one the player clicks on.

Found this in another Unity Answer, just altered it a teeny bit. Searching is good. :slight_smile:

function Update()
{
    if (Input.GetMouseButtonDown(1))
    {
        var hit : RaycastHit;
        if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit))
        {
            Destroy(hit.collider);
        }
    }
}

This would work better.