- Home /
Question by
darkcookie · Aug 02, 2013 at 01:03 PM ·
randomgeneral programming
Random Number generation
I have read various posts on unity answers on this topic but I'm yet to find an answer to my specific problem therefore i need to post a new question.(Re-post disclaimer)
My question is how can I go about generating a random number every time i press the "c" key?, the catch is that the number cant ever repeat itself.
Comment
Best Answer
Answer by robhuhn · Aug 02, 2013 at 01:16 PM
If you just need to Add numbers and increase the Size, use list.Add()
(Code not tested)
if(Input.GetKeyDown("c"))
{
do
{
MyNumber = rand.Next(1, 10000);
}while(NumbersProduced.Contains(MyNumber))
NumbersProduced.Add(MyNumber);
}
Hope that is what you meant.
Answer by aldonaletto · Aug 02, 2013 at 01:21 PM
The logic is wrong - you should draw random numbers until a value not yet used is found, then simply Add it to the list:
if(Input.GetKeyDown("c")){
do { // draw numbers until a non-repeated value is found
MyNumber = rand.Next(1,10000);
} while (NumbersProduced.Contains(MyNumber));
NumbersProduced.Add(MyNumber); // add new number to the list
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613111423im_/https://answers.unity.com/themes/thub/images/avi.jpg)