- Home /
Random Float Variable
This is horribly frustrating, maybe I'm just doing it wrong. I want to spawn a random(pre-made) object at an empty gameobject. I think that the easiest way to do this would be to call a random float number, like; 1-5. And then I'd use an if function to check the variable, and spawn the object if it's the right number.
Answer by aldonaletto · Jul 31, 2011 at 04:20 AM
You can use Random.Range(0,100) and compare it to the percentage limit:
if (Random.Range(0, 100) < 20){ var clone = Instantiate(...); }The chance to instantiate the object in this example is 20%
That will give you integers, if you want floats use Random.Range(0.0,100.0), but really how is it different from 1,5 like he suggests? He can use Random.value < 0.2 same.
The results would be the same, indeed, but I prefer to use Random.Range(0, 100) in my answers because it clearly resembles percentage, an intuitive concept for everybody. The normalized range 0..1 is more intuitive for us, technical people, but it's not so clear for surprisingly many people. And comparing Range(1,5) would fail if Range fell in the float version, what could occur if someone decided to use a float variable as one of the parameters ($$anonymous$$urphy's law...). But I had the same doubt as you: 5 objects to be drawn, or one object with 20% chance?
Hey Thanks! It works like a charm, I'm using it for terrain generation just so you know. I can't tell you how amazing it is to see trees pop up in different places all over the terrain whenever I click the play button!
I can't thank you enough!
Answer by DaveA · Jul 31, 2011 at 04:59 AM
Your question is ambiguous, can you explain more? Do you want to spawn ONE type of object at ONE place, on a 20% chance of doing so? If so, just compare Random.value to 0.2, if it's less, spawn away. Or do you want to spawn ONE type of an object at one of FIVE possible places? If so, you can have an array of 5 empty game objects and use that INTEGER to pick an element (0 to 4 by the way), and parent the new object to the chosen empty object. Or just assign the new object's position same as the chosen empty object.