Reputation:
I want to generate a unique random digit between 1 and 10. If a number gets repeated then the script should skip the number and try for another. If there are no unique numbers left then a message should be generated. Any logic to get this concept implemented?
public int number;
void Update () {
if(Input.GetKeyDown(KeyCode.A))
{
number= Random.Range(1,10);
}
}
EDIT: It is not a duplicate of the link the user posted since I am trying to generate unique number and if a particular number is repeated, the script ignores it and tries to look for another number.
Upvotes: 2
Views: 2605
Reputation: 9519
As guys suggested in the comments, shuffling might work:
public class Shuffler
{
private readonly Queue<int> _queue;
public Shuffler(int max)
{
_queue = new Queue<int>(Enumerable.Range(1, max).OrderBy(x => UnityEngine.Random.value));
}
public bool TryGetNext(out int item)
{
if(_queue.Count == 0)
{
item = -1;
return false;
}
item = _queue.Dequeue();
return true;
}
}
For the sake of completenes, adding MonoBehaviour
, e.g.
public class RandomNumber : MonoBehaviour
{
private Shuffler _shuffler;
public int number;
private void Awake()
{
_shuffler = new Shuffler(10)
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
if(!_shuffler.TryGetNext(out number))
{
Debug.Log("No valid Numbers");
}
}
}
}
Upvotes: 0
Reputation: 2408
public class RandomGenerator : MonoBehaviour
{
public int minNumber = 1;
public int maxNumber = 10;
private List<int> _validNumbers;
public int number;
private void Awake()
{
_validNumbers = new List<int>();
for (int i = minNumber; i <= maxNumber; i++)
_validNumbers.Add(i);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
if (_validNumbers.Count == 0)
Debug.Log("No valid Numbers");
else
number = GetRandomNumber();
}
}
private int GetRandomNumber()
{
var nextIndex = Random.Range(0, _validNumbers.Count - 1);
var result = _validNumbers[nextIndex];
_validNumbers.RemoveAt(nextIndex);
return result;
}
}
EDIT AFTER COMMENTS:
This question is very similar to this other question. But Unity.Random is different than System.Random.
The answers offered in the other question work here too. But we have more choices here.
Upvotes: 2