- Home /
Ramdomly spawn object
Could someone help me on making a script that ramdomly spawn a few objects? I am not that good at this.
I wanted to make a spawn script that would allow me to spawn a ramdom prefab that i've chosen in a ramdom location. For an example: I have a folder with 6 types of birds, and i want the script to spawn one of them in a random location from time to time.
How do i make the part of spawning a random game object of my chose? It wouldn't be a good thing if i saw a plant spawning in my front suddenly...
By using C# and Javascript you can create a variable with a fixed type of object. With this, i can spawn that object. But i didn't understand the part of spawning different objects.
Answer by Namey5 · Oct 05, 2016 at 07:07 AM
Well, where you would normally have a GameObject, you could use an array, and then instantiate that with a random number, i.e.
//in C#, because everyone seems to use it
public GameObject[] objects; //In the inspector you can set the size of this value and drag however many objects you want in here
//and then wherever you are spawning an object
int i = Random.Range (0, objects.Length);
Instantiate (objects[i], objects[i].transform.position, Quaternion.identity); //Use whatever random position/rotation you want here in the last 2 function variables
Answer by Kossuranta · Oct 05, 2016 at 07:21 AM
Make an array of game objects that you want to spawn and then define min and max positions in the game world for them. Then just spawn them using Random.Range.
public GameObject[] objects;
public Vector3 minPos;
public Vector3 maxPos;
void Update()
{
Vector3 position = new Vector3(Random.Range(minPos.x, maxPos.x), Random.Range(minPos.y, maxPos.y), Random.Range(minPos.z,maxPos.z));
Instantiate(objects[Random.Range(0, objects.Length)], position, Quaternion.identity);
}
Random.Range always returns at least 1 below the max value, so you shouldn't really subtract 1 from the max otherwise it will never spawn the last object.