How to generate GameObjects by random?

Hi to all,
I want to generate game objects at a specific period of time(5 second in this case), sometime yes, to be generated,sometime no, depending on a variable generated by random, but I don’t know why this doesn’t work as I would like, wich I find it strange.(The object is always generated and I want that sometime to be NOT generated).It is as the compiler would’t read the second part of “if()”.Is hard to belive that only 0 is generated, because I have also tried other things and I got the same wrong behaviour.

public GameObject animation;
private GameObject animation1;
int generate_or_not =0;
float generateTime=0.0f;

void Update(){
        generate_or_not=Random.Range(0,1);
        generateTime+=Time.deltaTime;
  if(((int)generateTime==5)&&(generate_or_not==1)){
        animation1=(GameObject)Instantiate (animation, Vector3(animation.transform.position.x-50, animation.transform.position.y,animation.transform.position.z), Quaternion.identity);
        generateTime=0.0f;
   }
}

I have tried to generated the variable generate_or_not in many places inside the code(inside Start(),inside Update(),inside “if()” or at the beginning of class) but nothing worked.
Another try was to generate/or not, objects after the previous generated objects has covered a specific distance(instead of waiting 5 seconds),but with no succes.
Please tell me how could I generate objects depending of the value of generate_or_not.Thank you in advance.

2 Answers

2

You must check the random value only when it’s time to decide if you generate or not - when the timer reached 5 seconds, in this case. Another point: you can use generateTime >= 5; that’s the way we usually compare time, so you will never miss the comparation due to some minor difference (I noticed you converted it to int to avoid this kind of error). The last point: Random.value returns float values between 0 and 1 (inclusive), and is better for this purpose than Random.Range - which in the int version never returns the max value.

void Update(){
    generateTime+=Time.deltaTime;
    if (generateTime >= 5){
        generateTime = 0.0f;
        if (Random.value <= 0.5f){ // check generate or not here
            animation1=(GameObject)Instantiate (animation, Vector3(animation.transform.position.x-50, animation.transform.position.y,animation.transform.position.z), Quaternion.identity);
        }
   }
}

You can change the chance to generate the object by altering the value to which Random.value is compared: 0.20f means 20%, 0.60 means 60% etc.

–

Random.Range(0,1) always returns 0. You need Random.Range(0,2), which returns 0 or 1 with equal probability.