Reputation: 3
I am picking and laying sprites on top of eachother, and I am doing this by picking them at random from an array. To give the illusion of them not reapeating, it is critical that they are not the same.
How do I achieve this, withouth adding to my array, and therefor putting my index out of the array bounds?`
//Random Sprite Value
int bloodSprite = Random.Range(0, 12);
int bloodSprite2 = Random.Range(0, 12);
if (bloodSprite == bloodSprite2)
{
// what do I write here? (if here)
}
Upvotes: 0
Views: 483
Reputation: 86
First get a random from 0 to 12 say x, then get a random from 0 to x - 1 or from x + 1 to 12. U can chose any.
int s1 = Random.Range(0, 12);
int s2 = s1 == 0 ? Random.Range(s1, 12) : Random.Range(0, s1);
You don't really need a loop for this.
Upvotes: 1
Reputation: 16069
do.. while
will be helpful over here
//Initialize default value to bloodSprite and bloodSprite2
int bloodSprite = int.MinValue;
int bloodSprite2 = int.MinValue;
do
{
//Random Sprite Value
bloodSprite = Random.Range(0, 12);
bloodSprite2 = Random.Range(0, 12);
//At the end, check condition in while.
}while(bloodSprite == bloodSprite2);
int.MinValue
: It is constant represents smallest possible value of an integer.
In above solution, We defined smallest possible value of int to bloodSprit, which will update it in side do..while()
loop
Why we used do..while()
loop?
do..while
loop at least once.Flow chart diagram:
Upvotes: 1
Reputation: 1
It should work for you.
while(bloodSprite == bloodSprite2)
{
bloodSprite2 = Random.Range(0, 12);
}
Warning: there is a very very low probability of ending up in infinite while loop.
Upvotes: 0