Item-Spawner in Unity2D

Hi. Im quite new to Unity and try to make a Item-Spawner. I just want to spawn one item every 45 seconds. It should also only spawn an item, if there isnt already one in game.
This is the code ive already written. The problem is, that after the 45 seconds are over, it doesnt spawn one, but an infinite amount of items.
Would appreciate some help. No real ideas anymore.

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

public class ItemSpawnSystem : MonoBehaviour
{
    public Transform[] spawnpoints;
    public GameObject item;

    public float timeBetweenSpawns = 45f;
    public float spawnCountdown;

    private void Start()
    {
        spawnCountdown = timeBetweenSpawns;
    }

    private void Update()
    {
        if(spawnCountdown <= 0)
        {
            SpawnItem();        
        }
        else
        {
            spawnCountdown -= Time.deltaTime;
        }
        return;
    }

    void SpawnItem()
    {
        Transform _sp = spawnpoints[Random.Range(0, spawnpoints.Length)];
        Instantiate(item, _sp.position, _sp.rotation);
    }
}

You only set spawnCountdown = timeBetweenSpawns once in Start(). You need to reset it after calling SpawnItem() n line 22, so put another spawnCountdown = timeBetweenSpawns there. This resets your countdown and will only spawn another item in 45 seconds.
You also never check if an item already exists, so currently with the above fix you’d spawn one item every 45 seconds regardless of whether an item already exists. To change this you need to keep track of the item. Introduce a new variable GameObject itemInstance, which you then fill with the return value from Instantiate.

What happens next depends on how you want the code to behave. If an item exists and 45 seconds passed you do not want a new item to spawn. Do you want the item to spawn instantly after the other item got destroyed, or do you want to check every 45 seconds if an item exists and spawn one if it does not? Or do you want the item to spawn exactly 45 seconds after the old instance got destroyed?
To spawn it instantly after 45 seconds passed as soon as the old instance got destroyed, simply add an itemInstance != null check to your if at line 20. To check every 45 seconds whether an item exists but only spawn a new one in case it does not, put another if-statement with the null check inside the line 20 one, which includes SpawnItem but excludes the countdown reset. To have another item spawn exactly 45 seconds after the last one got destroyed put a new if-statement above the others in Update, checking for itemInstance != null and setting the countdown back to 45s. You get the idea.
By the way you do not need the return statement at line 28.

Hope this helps :slight_smile:

1 Like

Thanks for the fast reply. It helped alot. :slight_smile: