- Home /
How to generate random objects?
Hi, I'm using java script to generate random objects like power-ups. So far my code is:
var spawn : GameObject;
var powers : GameObject[];
function start()
{
//the power up items are tagged as powers
powers = GameObject.FindGameObjectsWithTag("Powers");
generate();
}
function generate()
{
rand = Random.Range(1f,4f);
if(rand==1)
{
spawn = Instantiate(powers[1],
Vector3(10,0,0),
Quaternion.identity);
}
else if(rand==2)
{
spawn = Instantiate(powers[2],
Vector3(10,0,0),
Quaternion.identity);
}
//so on...
}
But nothing is generated at the position I wanted. Is there something wrong with my code? Any ideas?
Answer by Piflik · Jan 14, 2013 at 09:28 PM
Random.Range returns floats, if you use it with floats. Either use integers, or cast the result to integer, or you will never have any of these if statements true.
Then you probably create an integer that is greater than the array's maximum index (which is .Length - 1, since the array index starts at 0).
for testing, I only called two objects power[1],[2]. I have 5 objects. I initialized in console.
How you initialize the array is irrelevant, since you overwrite it in your first line. You store an array holding all Powerup items that are currently present in your scene, possibly this array is empty.
FYI, you can condense your code quite a bit by simply writing:
Instantiate(powers[rand], Vector3(10,0,0), Quaternion.identity);
ins$$anonymous$$d of all these if...else if...else if... statements.
can it only store the objects in scene? because the objects I want to spawn are not in scene. I want to add them to scene after the game started.
Your answer
Follow this Question
Related Questions
How do I make a game object spawn several times in semi-random locations? 1 Answer
I want to swap randomly 5 blocks (block has 5 diffrent color) and spawn in vertical line 1 Answer
Weighted Random Spawning 1 Answer
Enemies spawn on top of each other(C#)(Unity) 1 Answer
How do I randomly create 2 objects, each with a different shape and color? 1 Answer