Random.Range returns either 1 or 2
Whenever I run a "if (ChanceOfDrop == 3)" statement (ChanceOfDrop being set to Random.Range (1, 3)), it basically always returns a 2. Why is this?
My part of the code I am having a problem with:
ChanceOfDrop = 0;
ChanceOfDrop += Random.Range (1, 3);
if (ChanceOfDrop == 3) {
//if (Enemy1Clone == false) {
// Instantiate (wallDrop, Enemy.transform.position + (Enemy.transform.forward * 1), Enemy.transform.rotation);
//} else {
// Instantiate (wallDrop, Enemy1.transform.position + (Enemy1.transform.forward * 1), Enemy1.transform.rotation);
//}
//Instantiate (wallDrop, Player.transform.position + (Player.transform.forward * 1.25f), Quaternion.identity);
WallDropTrans.position = this.transform.position + (this.transform.forward * 1.0f);
//WallDropTrans.rotation = Player.transform.rotation;
} else {
Debug.Log ("required int not received (wallDrop). (int received: " + ChanceOfDrop + ")");
}
That's why :
private void Update()
{
Debug.Log("Range 1 - 3: " + Random.Range(1, 3));
}
Random.Range(1, 4)
is what you looking for
Ohhh... Im an idiot... Random.Range (1,3)
means any number in BETWEEN 1 and 3... Thank you so much for clearing it up lol
Answer by Caruzo · Oct 05, 2017 at 10:39 PM
If you are trying to make the chance of drop 33% as I'd assume so, you could easily do
ChanceOfDrop = Random.Range (1, 4);
if (ChanceofDrop == 3) {
//your code
}
I have also noticed that even though in the documentation it says that Random.Range( min, max) is inclusive, it seems to be only including the min but not the max.
No. The documentation says "Note that max is exclusive, ..." for float value is inclusive.
Source : https://docs.unity3d.com/ScriptReference/Random.Range.html
This is indeed true, however in the $$anonymous$$onoDevelop itself, it shows information only about the float and not about integers. This is where I was confused. Thanks for pointing out :)
Answer by MaxGuernseyIII · Oct 05, 2017 at 11:15 PM
The Unity implementation of System.Random works and Next(int) seems like it will drive the behavior you want.
Just replace "maxValue" with "numberOfOptions" in your mind.
var random = new Random();
var dieRoll = random.Next(3);
if (dieRoll == 0) { /* do special 1-in-3 case */ }