- Home /
The question is answered, right answer was accepted
How to exclude int values from Random.Range?
Hey,
I'm trying to have an Enemy move in random directions.
What I've done is set up 8 arrays of ints and for each value from the array I have a movement direction put in place.
My enemy will choose a random direction each time it hits one of the 4 walls (left,right,top,bottom). The problem is that if for the top wall I need for example ints 1,3,5 (which would be the accepted directions), how could I use Random.Range to make it select a value of either 1, 3 or 5 and never 2?
Regards, Eugen
Hey!
I've created an asset designed exactly for that case (it's paid).
https://assetstore.unity.com/packages/tools/input-management/random-exclude-133786
Feel free to try it!
Answer by whydoidoit · May 09, 2013 at 01:37 PM
var validChoices = [1,3,5];
function GetRandom() : int
{
return validChoices[Random.Range(0, validChoices.Length)];
}
That's great! $$anonymous$$arking it as an answer, although I'm receiving a Warning: Implicit downcast from 'object' to 'int'. Any way to get around it?
I have to mention that I did not use the code in the exact same way you have provided.
Oh sure just make validChoices:
var validChoices : int[] = [1,3,5];
That's not the cause of the warning. var validChoices = [1,3,5]
already returns an int[] array (because it's an array containing only integers); the ": int[]" is superfluous. The code provided does not result in any warnings.
After making defining them as int[] it works perfectly. @Eric, as I mentioned my code was a bit modified.
Answer by pad406 · May 09, 2013 at 01:43 PM
I think the simplest way is to create a function where you pass the direction that you don't want chosen and it then re-tries the random number if that is chosen.
eg.,
int GetNewDir(int NotThisDirection)
{
int newDir;
newDir = Random.Range(1,8);
while (newDir == NotThisDirection)
{
newDir = Random.Range(1,8);
}
return newDir;
}
Bad practice. In THEORY this while loop can take FOREVER and never randomize the expected numbers.