Spawner

The code works here but not how i expect it too. Its spawning objects far earlier than expected to i set the spawnRate to 2 seconds and time at 0. but its spawning 100s and 100s of the same object every millisecond prtty much

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

public class SpawnEnemy : MonoBehaviour
{
    public GameObject Enemy;
    public float spawnRate = 2;
    private float timer = 0;
   
    // Start is called before the first frame update
    void Start()
    {
        SpawnEnemys();
    }

    // Update is called once per frame
    void Update()
    {
        if(timer < spawnRate)
        {
            timer = timer + Time.deltaTime;
        }
        else
        {
            SpawnEnemys();
            timer = 0;
        }
    }

    void SpawnEnemys()
    {
        Instantiate(Enemy, transform.position, transform.rotation);
    }
}

I think you wrote a < when you meant to write an >.

1 Like

It’s because you have attached your SpawnEnemy script onto your Enemy GameObject - I can see it in your screenshot. Therefore every Enemy that gets instantiated runs the SpawnEnemy script and spawns more enemies.

You should have a dedicated spawner game object and only game object should have the SpawnEnemy script on it.

Edit: also, you didn’t really need to create a second topic for this - you should have just continued the discussion in your original one.

what do you mean have a dedicated spawner game object? like create another gameobject i tried that and put the script on that but then crashed my computer again.

Your enemy has the spawn enemy component.

Thus whenever you spawn an enemy, it will spawn another enemy, and so on and so forth to infinity.

So make them two different game objects.

ahh yes ty i see now