- Home /
Generating objects randomly, only one will Instantiate
Hi,
I'm trying to create a random number that then goes through an if statement to decide which object to spawn, but for some reason only the first of the two objects ever get created.
Here's the code
var myTimer : float;
var Obstacle : GameObject;
var Obstwo : GameObject;
var ObsChance : float;
function Start () {
myTimer = Random.Range(0.0, 3.0);
}
function Update () {
ObsChance = Random.Range(0.0, 100.0);
if (myTimer > 0){
myTimer -= Time.deltaTime;
}
if (myTimer <= 0){
if (ObsChance <= 50){
var obstacleClone : GameObject = Instantiate(Obstacle, transform.position, transform.rotation);
}
else if (ObsChance > 50){
var ObstwoClone : GameObject = Instantiate(Obstwo, transform.position, transform.roatation);
}
myTimer = Random.Range(0.0, 3.0);
}
}
Not sure why the second if never triggers.
I can't find the error. Check if the Obstacle and Obstwo have different objects. By the way, why you are using a float for the random value?
Double check you are using the correct prefabs when yo are assigning it to your gameobject location of your script.
Here is a nicer time which is in my opinion simpler and easy to read.
float timer;
int waitingTime;
void Update()
{
timer += Time.deltaTime;
if(timer > waitingTime)
{
//Action
timer = 0;
}
}
For fifty-fifty you can do:
if (Random.Range(0,2) == 0) {
// Do one thing
}
else {
// Do another
}
The integer version of Random.Range is exclusive of the last value.
Why are you changing ObsChance every frame? It seems like it would be more efficient to move line 9 to line 15. Have you tried printing the value of ObsChance before running the spawn code?
Your answer
Follow this Question
Related Questions
random object creation 1 Answer
How do re-randomize Random.seed after setting it? 3 Answers
Random enemy generator 1 Answer
How to instantiate prefabs at random postions in 2d 1 Answer
Objects appear randomly in specific length and height 1 Answer