- Home /
Spawning Object at Random Points in an Array?
Hi
Never be taught about arrays in College so everything I know has been crafted together from what I've seen and heard. Done loads of googling and haven't found anything useful of what I want to do.
Got a prefab and want to spawn it random locations. I've make a load of spawn points where I wouldn't mind it spawning so I decided to put them in an array. I've seen a few ways to pick a random value from an array but won't work with mine.
I have set the array up with find with tags so i just need it to randomly pick a transform from that array.
Can anyone help please.
public GameObject hazard;
public GameObject[] hazardSpawn;
public int hazardCount;
public int multiply = 2;
public float spawnWait;
public float startWait;
public float waveWait;
void Start ()
{
hazardSpawn = GameObject.FindGameObjectsWithTag ("HazardSpawn");
StartCoroutine (SpawnWaves ());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Transform spawnPoint = hazardSpawn[Random.Range(0, hazardSpawn.Length)]; //this is what I tried
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, hazardSpawn, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
//hazardCount needs to be multiplied here (my little reminder)
yield return new WaitForSeconds (waveWait);
}
}
}
is hazardCount definitely set to something other than 0, at the moment it will default to 0 and your for loop will therefore never run.
Answer by KellyThomas · Aug 12, 2014 at 02:05 PM
This snippet is not actually using the position
of your spawnPoint
:
Transform spawnPoint = hazardSpawn[Random.Range(0, hazardSpawn.Length)]; //this is what I tried
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, hazardSpawn, spawnRotation);
Try passing these values to your Instantiate()
call:
Instantiate (hazard, spawnPoint.position, spawnRotation);
That code is right, though it might lack a little something:
Transform spawnPoint = hazardSpawn[(int)Random.Range(0, hazardSpawn.Length)];
Random.Range returns a float but you can only access arrays with integers. Apart from that, you should follow the advice of the other user who gave you an answer.
Actually, if you call it with ints, the int overload is called, and it returns an int, so no need for casting.
Right, I missed that part in the documentation. Sorry!
Cheers for that. but how come I get this error with this line of code.
error CS0029: Cannot implicitly convert type UnityEngine.GameObject' to
UnityEngine.Transform'
Transform spawnPoint = hazardSpawn[Random.Range(0, hazardSpawn.Length)];
Transform spawnPoint = hazardSpawn[Random.Range(0, hazardSpawn.Length)].transform;