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”
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?
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.