- Home /
How do Generate Random Unique int ?
Hi Everybody, It was a really cool day, untill I decided do generate Random And Unique coordinates, for props spawning.
So I need a 5 Random ints, from Range between 0 and Array"PropZoneX" Length. I decided to store values, but I can't resolve, how to make values unique... Please Help to find a solution
int XpropZoneIndex;
List<int> GeneratedValuesX = new List<int>();
int GetRandX(bool Active = true)
{
XpropZoneIndex = Random.Range(0, PropsZoneX.Length);
GeneratedValuesX.Add(XpropZoneIndex);
return XpropZoneIndex;
}
Thanks for helping, Have a nice day!
It looks like you add the int to a list, but you don't check against that list to make sure the int is unique. You may require a for loop and a while loop. Here is an example: http://answers.unity3d.com/questions/715799/how-to-generate-unique-random-number.html
Thank you for your reply, but I Have Already tryied exactly this answer solution, but in my case it's returns a dublicates anyway :C
Answer by EvilTak · Mar 10, 2017 at 11:19 AM
You can guarantee that Random.Range(min, max)
will return n - m + 1
unique integers. In your case, that would be PropsZoneX.Length + 1
integers. If it doesn't return unique integers for that many method calls, there's something wrong with the Unity implementation. If so, read on.
First, you can use the System.Random
class to generate random numbers instead. Bear in mind that this may not work on all platforms, and that you initialize the instance only once. Something like:
private System.Random random = new System.Random();
int GetRandX(bool Active = true)
{
XpropZoneIndex = random.Next(0, PropsZoneX.Length);
GeneratedValuesX.Add(XpropZoneIndex);
return XpropZoneIndex;
}
Second, you can use a HashSet
(and convert that to a list later if needed):
HashSet<int> randomIntSet = new HashSet<int>();
while(randomIntSet.Count < 5) {
randomIntSet.Add(Random.Range(0, PropsZoneX.Length));
}
GeneratedValuesX = randomIntSet.ToList(); // You'll need to use System.Linq for this
Your side note is actually wrong ^^. The int version of Random.Range has the $$anonymous$$ value inclusive but the max value exclusive. Read the docs carefully, there are two different overloads on this page.
Ah, thanks. I was wondering where the int version was in the docs. I'll fix the answer.
Your answer
Follow this Question
Related Questions
Increase score upon an enemy's death 2 Answers
How to assign random int values to gameobjects 2 Answers
Choosing random number of different gameobjects 2 Answers
Have a problems with a values 1 Answer
Multiple Cars not working 1 Answer