Home > OS >  Unity: How to destroy an Instantiated object in a different function
Unity: How to destroy an Instantiated object in a different function

Time:12-04

I'm trying to make a game which is spawning an object and after the object is destroyed, another object spawns right away. But right now I'm trying to destroy an instantiate object in a different function, and it is not working.

`

    public GameObject[] food;
    public Vector3Int spawnPosition;

    public void Start()
    {
        SpawnFood();
    }

    //Spawning food 
    public void SpawnFood()
    {
        int random = Random.Range(0, food.Length);
        GameObject clone = (GameObject)Instantiate(food[random], this.spawnPosition, Quaternion.identity);
    }

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.C))
        {
            Destroy(this.gameObject);
        }
    }

`

I have tried to do some research on this and still, I can only find the solution for destroying an object inside the same function as the Instantiate.

CodePudding user response:

When you call Destroy(this.gameObject), the game object the script attacting to will be destroyed, and after that you cannot call the script.

I guess what you want to destroy is the food game object, not the game object the script you showed here attacting to.

A quick adjustment to suit your need maybe :

...
private GameObject clone
...
private void Update()
{
    if(Input.GetKeyDown(KeyCode.C))
    {
        if (clone != null)
          Destroy(clone);
    }
}

And as @Daniel seggested, if you will repeatedly instantiate/destroy food game object, the better way would be just use the same food object and change it's properties (e.g. location...) to create the new food game object pop-up illusion.

The key idea here is called Object Pooling.

CodePudding user response:

Here is your answer :

declare a public Gameobject:

public GameObject clone;

and replace

GameObject clone = (GameObject)Instantiate(food[random], this.spawnPosition, Quaternion.identity);

with

GameObject clone = Instantiate(food[random], this.spawnPosition, Quaternion.identity);

and then you can destroy in another function or class

public void DestroyFood()
{

Destroy(clone);

//you can instantiate another gameobject here

}
  • Related