(C#) Problem With Random Number Generator
private int randomIndex = 0;
public void GiveIndex()
{
float randomValue = Random.value;
if (randomIndex >= 0 && randomIndex < 5)
{ // FIRST SET starts here
if (randomValue <= 0.5) { randomIndex = 0; }
if (randomValue > 0.85) { randomIndex = Random.Range(1, 5); }
if (randomValue > 0.5 && randomValue <= 0.85) {randomIndex = 5;}
} // FIRST SET ends here
if (randomIndex >= 5 && randomIndex < 11)
{ // SECOND SET starts here
if (randomValue <= 0.5) { randomIndex = 6; }
if (randomValue > 0.85) { randomIndex = Random.Range(7, 11); }
if (randomValue > 0.5 && randomValue <= 0.85) {randomIndex = 0;}
} // SECOND SET ends here
}
Code explanation:
This is a piece of code that's basically supposed to set randomIndex to a certain number with some probability, There are two sets of numbers (from 0 to 5 in first set and from 6 to 10 and 0 in second) it starts drawing in first set (because randomIndex initial value is 0) and if it happens to draw 5 from first set, then it goes to second set and draws numbers from 6 to 10 and 0, if it happens to draw zero it goes back to draw from first set and so on. The number that is drawn becomes randomIndex.
Problem:
Code seems to ignore the second set. If it draws 5 in first sets it doesn't go to draw from the second but still moves around first. Even if I set randomIndex initial value to eg. 8 it still draws from first set only.
Answer by Dragate · Oct 16, 2017 at 01:34 PM
You get a randomValue at start. If it happens to be larger than 0.5 and smaller (and equal) than 0.85, randomIndex is assigned 5 and must draw from second set. But you do not get another randomValue, which means it's still in the range of (0.5,0.85]. That corresponds to randomIndex = 0 in the second set. The solution is do another randomValue = Random.value; upon entering the second set.
Thank you for the solution. Thanks to you I found another problem and fixed it, but second one wasn't affecting piece of code shown here. I needed this to make procedurally generated and smoothly changing bioms and now all seems to work.