Search code examples
c#unity-game-engineinstantiation

How can I destroy a cloned object (Complicated question, see body of my question to understand)?


I have a 3d game and when my player is activating a button, it spawn a clone of an object (using instantiate). I dont want my player to be able to have more than 1 box(clone) at a time. Therefore, If the player click the button to spawn a clone, and there is already a clone present, I want to destroy the already present clone. I will put the code I use to spawn the clone down bellow. (Note that "transform.position" in both void OnMouseDown and OnMouseUp is used to change the apparence of the button when pressed)

public class Button : MonoBehaviour {

public Rigidbody box;

void OnMouseDown()
{
    transform.position = new Vector3(-3.5f, 1.45f, 7.0f);

    Rigidbody clone;
    clone = Instantiate(box, new Vector3(0f, 10f, 11f), transform.rotation);
}

void OnMouseUp()
{
    transform.position = new Vector3(-3.5f, 1.5f, 7.0f);
}

}


Solution

  • You need to store your "clone" in a class reference like you do for your original box, and check if it's not empty. If its present then destory.

    public class Button : MonoBehaviour {
        public Rigidbody box;
        public Rigidbody clone;
    
        void OnMouseDown()
        {
            transform.position = new Vector3(-3.5f, 1.45f, 7.0f);
            if(clone != null)
            {
                 Destroy(clone);
            }
            clone = Instantiate(box, new Vector3(0f, 10f, 11f), transform.rotation);
        }
    
        void OnMouseUp()
        {
            transform.position = new Vector3(-3.5f, 1.5f, 7.0f);
        }
    }