- Home /
Instantiate position from four options.
Hi, so I have to have zombies spawn at one of four spawners. My problem is that I don't know how to put in more than one location as the spawn locations. I tried doing
Instantiate(Zombie, (spawn1 || spawn2 || spawn3 || spawn4), etc...)
but that did not work. Is there any other way I can do this?
I like how you think, but unfortunately OR works with boolean arguments and thus are those spawnpoints converted to true/false.
Answer by Lockstep · Apr 07, 2013 at 12:09 AM
This is quite simple just make an array which contains your possible spawn locations and pick one randomly. The code could look like this (c#):
public Transform[] spawnPoints; //assign the spawnpoints in the inspector or during Start
void SpawnZombie(){
int pick = Random.Range(0, spawnpoints.Length); //select one spawnpoint randomly
Instantiate (Zombie, spawnPoints[pick].position, spawnPoints[pick].rotation);
}
var spawnPosition = new Array (spawnOne.transform.position, spawnTwo.transform.position, spawnThree.transform.position, spawnFour.transform.position);
Instantiate(zombie, (spawnPosition[Random.Range(0, 3)]) + Vector3((Random.Range (0, spawnOne.renderer.bounds.size.x)) / 2, 0.5, (Random.Range (0, spawnOne.renderer.bounds.size.x)) / 2), Quaternion.Euler(0,0,0));
For some reason in the Instantiate it is telling me that the
(spawnPosition[Random.Range(0, 3)])
is an object and won't compile because it says that Object + Vector 3 is not allowed.
the js Array class can store any object, thus spawnPosition[x] is a general object. You need to cast it to Vector3
if you want to use the Array class
Instantiate(zombie, ( (Vector3) spawnPosition[Random.Range(0, 4)]) + Vector3(((Random.Range (0, spawnOne.renderer.bounds.size.x)) / 2, 0.5, (Random.Range (0, spawnOne.renderer.bounds.size.x)) / 2), Quaternion.identity);
I'd still recomend the builtin array in my example since you have better controll over the type. The cast will fail if you accidentially add an object to the array which is not a Vector3. The sysntax would be:
var spawnPoints : Vector3[];
function Start(){
spawnPoints = [spawnOne.transform.position, etc];
}
There is also a page on different arrays on the wiki.
Also take note, that the right number of Random.Range
is exclusive if you use integers. Thus you need Random.Range(0,4)
or better Random.Range(0, spawnPosition.length)
I think his only fault were the parenthesis around spawnPosition[Random.Range(0, 3)]. Try removing those.