1
\$\begingroup\$

I am new to game development. I am trying to change the player prefab every X seconds. For that, I am destroying the previously spawned prefab and instantiating a new prefab. But I don't know how to DESTROY THE PREFAB (not the empty game object on which the script is attached)

This is my code :

[SerializeField]
public GameObject[] objectToSpawn;

public float ChangeInterval = 5;
public float timer;


private void Update()
{
    int Rand = Random.Range(0, objectToSpawn.Length);
    GameObject spawnPrefab = objectToSpawn[Rand];

    timer += Time.deltaTime;
    if (timer >= ChangeInterval)
    {
        
        Instantiate(spawnPrefab, transform.position, Quaternion.identity);

        timer -= ChangeInterval;
       }
    Destroy(gameobject);
    


}

Please tell me how can I destroy the prefab. Also is this the correct approach for it?? Thank You.

\$\endgroup\$
1
  • \$\begingroup\$ You destroy right away the current one. If it should be destroyed after X time, you should place the destroy in the timer loop as well \$\endgroup\$
    – Zibelas
    Mar 25, 2023 at 18:30

1 Answer 1

1
\$\begingroup\$

What you want is not to destroy the prefab (the asset in your file system that tells you what properties this object should have), but to destroy the spawned instance of that prefab - the new copy of it that you've created in your scene.

Instantiate() returns a reference to this instance, so save it in a variable so you know what object to destroy later.

You can also do this without an Update() method or timer variable, like so:

// Use a coroutine instead of ticking Update every frame.
IEnumerator Start() {
    // Store the interval in seconds between prefab changes.
    var delay = new WaitForSeconds(ChangeInterval);

    // Repeat forever.    
    while (true) {
        // Select a prefab to spawn only when it's time to spawn one.
        int prefabIndex = Random.Range(0, objectToSpawn.Length);
        var prefab = objectToSpawn[Rand];

        // Spawn that prefab and capture a reference to this new copy.
        var instance = Instantiate(prefab, transform.position, Quaternion.identity);

        // Return control to the main game loop until it's time to spawn again.
        // (This prevents the infinite loop from making the game hang).
        yield return delay;

        // Delete the last instance we spawned.
        Destroy(instance);

        // Resume from the top of the loop.
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .