- Home /
Spawning Creatures
I'm trying to figure out a spawn code and I just got lost. I'm trying to set a spawn timer but it doesn't work. My script just spawns all 10 creatures at the same time. Can you help me with that?
Here is my code:
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour
{
public GameObject monsterPrefab; // Set this in inspector to the monster prefab.
public int count = 0;
private float timeSinceLastSpawn = 0;
GameObject monsterInstance;
Transform[] spawnpoints;
void Update()
{
spawnpoints = GetComponentsInChildren<Transform>();
while (count<10)
{
if (timeSinceLastSpawn <= 0)
{
Spawner();
timeSinceLastSpawn = 4;
count++;
}
timeSinceLastSpawn -= Time.deltaTime;
}
Debug.Log(timeSinceLastSpawn);
}
void Spawner()
{
int index = Random.Range(0, spawnpoints.Length - 1);
var spawnpoint = spawnpoints[index];
monsterInstance = (GameObject)Instantiate(monsterPrefab,
spawnpoint.position,
spawnpoint.rotation);
}
}
static function Range($$anonymous$$: int, max: int): int; Description
Returns a random integer number between $$anonymous$$ [inclusive] and max [exclusive] (Read Only). If max equals $$anonymous$$, $$anonymous$$ will be returned. The returned value will never be max unless $$anonymous$$ equals max
Random.Range problem, if the upper range of an INT random range is never reached. So, if spawnpoints.Length = 1 you get 0-0, so what if there are no children?
spawnpoints = GetComponentsInChildren();
Consider a for loop ins$$anonymous$$d of a while loop, or really if you want progressive spawning dont handle it in a loop at all.