Hi, i was wondering if its possible to make a script that says to instantiate one of say… 5 random gameObjects? I know how to do random number selection, but can it do like “instantiate (random…, position, rotation);”?
Yes. And also, “yes” to the second question too.
Yes, all you would need to do is place all of the objects you want to randomly select from into the resources folder then use the Resources.Load functions to pull them into an array. From there generate a random number within the range of the array and instantiate the item at that index point.
Instantiate(objects[Random.value * objects.Length], position, rotation);
There is a sting in the tail of this, unfortunately, because Unity’s Random.value can return a value of 1, unlike most RNGs. This means that you will occasionally get an out-of-range index for the array. It is safer to use Random.Range to generate the random array index:-
Instantiate(objects[Random.Range(0, objects.Length)], position, rotation);
and you should also do something like
if( objects != null objects.Length > 0 )
you’ll still get exceptions with random.range(int,int) if the array is null or empty.