- Home /
Random spawn at different locations
Hi!, Im trying to spawn a cylinder at different locations, here is what I have, am I missing something?
public Transform[] possibleSpawnPositions;
public GameObject objectTypeToSpawn;
public void SpawnNewObject() {
Transform spawnPointReference = GetSpawnPointReference();
Transform newObject = Instantiate(objectTypeToSpawn, spawnPointReference.position, spawnPointReference.rotation) as Transform;
}
public Transform GetSpawnPointReference() {
int randomIndex = Random.Range(0, possibleSpawnPositions.Length);
return possibleSpawnPositions[randomIndex];
}
}
Answer by YoungDeveloper · Dec 13, 2013 at 04:42 AM
Have you added that cylinder mesh in inspector, same as all spawn point? And array first element starts from 0, so it should be:
possibleSpawnPositions.Length-1;
Here is a similar question i answered.
http://answers.unity3d.com/questions/534933/random-spawn-random-prefab.html
Remember, for Random.Range using integers, Returns a random integer number between $$anonymous$$ [inclusive] and max [exclusive]. I think they did this so one could use myArray.Length
http://docs.unity3d.com/Documentation/ScriptReference/Random.Range.html
I cannot see a problem with the code! $$anonymous$$aybe it is as you suggested, the array is not populated in the inspector.
Yeah everything in the inspector is added but it doesn't seem to work
Oh, are you actually calling the method SpawnNewObject() from anywhere?!
Add a Debug.Log in each method to see ....
public Transform[] possibleSpawnPositions;
The array is empty, thats why you are not able to spawn.
I checked your script and it is throwing me an error IndexOutOfRangeException: Array index is out of range.
Either you have to add some game object in possibleSpawnPositions[] or spawn in some random positions
And where are you calling SpawnNewObject()?
Your answer
Follow this Question
Related Questions
make 2 object not collide? 2 Answers
Create a cube relative to camera & mouse position. 1 Answer
zombie network spawn! help" 0 Answers
grid checking for objects 1 Answer
No appropriate version of 'UnityEngine.Object.Instantiate' 1 Answer