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];
}

}

1 Answer

1

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.

Yeah everything in the inspector is added but it doesn't seem to work

Remember, for Random.Range using integers, Returns a random integer number between min [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! Maybe it is as you suggested, the array is not populated in the inspector.

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()?

Thanks! I just needed to call SpawnNewObject!!