My instantiate doesnt work properly

Hello! Im trying to make some enemies walk in a straight line towards the player and if any of them hit the player, the game ends
.
To do this i thought it was best to instantiate the enemies in a certain position and then add a force to them or just update their position (but i didnt get that far yet)

Now the problem is that the enemies keep spawning without a delay, even though i added a wait for seconds and i got no idea why this happens. I know im calling it in the update method but i couldnt find another better solution.

Here’s the script:

public class enemies : MonoBehaviour
{
    public GameObject enemy;
    public GameObject helper;

    public GameObject position;

    private string[] Enemies = new string[] { "Helper", "Enemy" };

    private Vector2 force = new Vector2(5f, 0f);

    private void Update()
    {
        StartCoroutine("Spawner");
    }

    IEnumerator Spawner()
    {
        string randomly_chosen = Enemies[Random.Range(0, Enemies.Length)];

        if (randomly_chosen == "Helper")
        {
            Instantiate(helper, position.transform.position, Quaternion.identity);

            yield return new WaitForSeconds(5f);
        }

        else
        {
            Instantiate(enemy, position.transform.position, Quaternion.identity);

            yield return new WaitForSeconds(5f);
        }
    }
}

Im pretty sure this is a very simple question but i just cant figure it out by myself.
Any help is apriciated! (also please mind the typos or grammar mistakes its 2am)

Update() runs every frame. Therefore you’re starting a new coroutine in every frame. Also, each coroutine only spawns one enemy, then waits 5 seconds, then finishes running.

Try starting the coroutine once in Start(). Then put your spawning code that’s inside the coroutine into a while loop so it runs repeatedly. Just make sure you don’t run it without a yield return statement in the loop or Unity will freeze!

Happy coding!

1 Like

You called it in update. So every frame you are starting a coroutine

Thanks a lot! I got it to work even i a few lines of code