[SOLVED]Instantiate will not work(Spawn infinity obj)

Hello
I need help using Instantiate.
When i use this code:

 public GameObject enemy;
    public Transform[] enemySpawner;

    void Update() {
        for (int i = 0; i < 1; i++) {
            Instantiate(enemy, enemySpawner[i].position, enemySpawner[i].rotation);
        }
    }

Spawn it infinity Objects it is why it was inside the “void Update” or it is the “for”

Thanks:)

Update runs every frame, so your code will keep instantiating a new enemy every frame and never stop. Maybe putting the same code in Start() would work like you want?

2 Likes

Thanks for the reply
I will make that every 5f seconds spawn an obj.
I will try

I solved the problem right now @kdgalla Thanks.
if someone needs

 public GameObject enemy;
    public Transform[] enemySpawner;

    void Start() {
        StartCoroutine(SpawnerTimer());
        for (int i = 0; i < 1; i++) {
            Instantiate(enemy, enemySpawner[i].position, enemySpawner[i].rotation);
        }
    }

    IEnumerator SpawnerTimer() {
        yield return new WaitForSeconds(5);
        Start();
    }

to spawn every second a object here is my script

That would work, but I’d probably write it this way:

 public GameObject enemy;
    public Transform[] enemySpawner;

    void Start() {
        StartCoroutine(SpawnerTimer());
    }

    IEnumerator SpawnerTimer() {
    for (int i = 0; i < 1; i++) {
            Instantiate(enemy, enemySpawner[i].position, enemySpawner[i].rotation);
        }
        yield return new WaitForSeconds(5);
    }
1 Like

Ok Thanks

Take a look again sir… I believe you left out the loop in your IEnumerator, plus your for() loop has a count of only 1 :slight_smile:

After you fix, just like this post and I will delete my post.

1 Like

Oh right. After a few minutes of gawking at the screen wondering why it doesn’t work, I’d probably write it like this:

public GameObject enemy;
    public Transform[] enemySpawner;

    void Start() {
        StartCoroutine(SpawnerTimer());
    }

    IEnumerator SpawnerTimer() {
     while(true)
      {
        for (int i = 0; i < enemySpawner.Length; i++) {
            Instantiate(enemy, enemySpawner[i].position, enemySpawner[i].rotation);
             }
             yield return new WaitForSeconds(5);
        }
  }

Note: when you iterate over an array using a for loop, use the array’s built-in Length property, instead of 1 or just a number. That way it will still work without updating, no matter what size your array is.

1 Like