- Home /
Random instantiate?
Hello. I am trying to make a script where there are multiple possible object variants to spawn (in this case enemy types) and the it randomly spawns a set number of them at repeating intervals, but when I try my script I get the error " No appropriate version of 'UnityEngine.Random.Range' for the argument list '(UnityEngine.GameObject, UnityEngine.GameObject, UnityEngine.GameObject)' was found."
How can I fix my script? Thanks :)
var A : GameObject; var B : GameObject; var C : GameObject;
if (Projectile.Defeat < 200 && Projectile.Defeat > 80) { yield WaitForSeconds(5.0); Instantiate(Random.Range(A,B,C), position, Quaternion.identity); }
EDIT For being organized, is there a better way to instantiate multiple objects other than copying the instantiate part of the script like this?
Instantiate(objs[(Random.Range(0, 3))], new Vector3(Random.Range(481.5735, 559.3441), -791.811, Random.Range(380.1254, 420.0663)), Quaternion.identity);
Instantiate(objs[(Random.Range(0, 3))], new Vector3(Random.Range(481.5735, 559.3441), -791.811, Random.Range(380.1254, 420.0663)), Quaternion.identity);
Instantiate(objs[(Random.Range(0, 3))], new Vector3(Random.Range(481.5735, 559.3441), -791.811, Random.Range(380.1254, 420.0663)), Quaternion.identity);
Answer by Zib Redlektab · Nov 28, 2010 at 03:24 AM
You could make an array of GameObjects instead, get a random number between 0-3, and use it as the index, I think.
var objs : GameObject[];
// Populate array with objects A, B, and C here
if (Projectile.Defeat < 200 && Projectile.Defeat > 80) { yield WaitForSeconds(5.0); Instantiate(objs[(Random.Range(0, objs.Length))], position, Quaternion.identity); }
To do a random position as well, you could replace 'position' above with a random Vector3, within a range you decide (xMin & Max, etc):
new Vector3(Random.Range(xMin, xMax), Random.Range(yMin, yMax), Random.Range(zMin, zMax))
And to create more than one object (3 objects, for example) :
...
yield WaitForSeconds(5.0);
for (var i = 0; i < 3; i++) {
Instantiate(objs[(Random.Range(0, objs.Length))], position, Quaternion.identity);
}
You should use "`var objs : GameObject[];`" ins$$anonymous$$d of Array, remove $$anonymous$$athf.Round, and use "`Random.Range(0, objs.Length)`" ins$$anonymous$$d of hard-coding the upper range
Noob question, but how do I "Populate array with objects A, B, and C"
If you used my code above, you should now have an Array in the inspector called objs, and you can fill it there. Otherwise, just use objs[0] =
$$anonymous$$y bad, I guess I should try a script before saying "I have no idea what that means" :). Anyways, thanks for your help Zib and Eric.
Ive run into another problem, is there any way to instantiate the objects at different points within the position range? I tried copying the instantiate part of the script and although the objects spawned are different, they all spawn at the same place.
Your answer