How can I Instantiate one object and then when it is destroyed instantiate the object again

So Im trying to make Snake and I want to instantiate a food object within my bounds. currently I can do that but it keeps creating new objects and doesn’t stop. this is because its in the update function and I don’t have any code that stops it. My idea is to instantiate a single object in Start() and then use OnTriggerEnter2D() to detect if the object is destroyed and then instantiate new objects in a similar fashion.

Here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Food : MonoBehaviour
{
    private Vector3 screenBounds;
    private Vector2 randomRange;

    public GameObject food;


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        randomRange = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));

        Instantiate(food, randomRange, Quaternion.identity);
    }

    private void OnTriggerEnter2D(Collider2D col)
    {
        if(col.tag == "Player")
        {
            Instantiate(food, randomRange, Quaternion.identity);
        }
    }

}

Please Help

Thanks

Hello @noah3322
I’d suggest to take a look at OnDestroy() method.

Or you can us a coroutine when you enter the trigger so you’ll instantiate a new object, wait for a second, and destroy the current one.

OnDestroy() is for when the scene is destroyed. Not objects.

I got it to work by having it instantiate an new game object inside a different script. Where the snake collides with the food inside the snake script i have an OnTriggerEnter2D() function and

if(col.tag==“Food”){Instantiate(food,randomRange, Quarternion.identity);}

That seemed to work