Lets say I have integers between 1 and 10. First time I chose randomly integer with Random.Range(1,10)
. Let’s say it returns 8. Now I want to get number again from 1 to 10, but I want that it would not return 8 now. So basically I want that each time number is rolled, I want that it won’t be rolled again on next roll. How it would be easiest to implement this?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomNumber : MonoBehaviour {
List<int> numberList = new List<int>();
void Start () {
int numberAmmount = 10;
while(numberAmmount > 0){
numberList.Add(numberAmmount);
numberAmmount--;
}
}
int GetRandomNumber(){
if(numberList.Count == 0)
return -1; //there are no more numbers left
int i = Random.Range(0,numberList.Count);
int toReturn = numberList*;*
-
numberList.RemoveAt(i);*
-
return toReturn;*
- }*
}
Here you go, I didn’t test this tho.
Just save the last rolled int as a variable
int oldInt = 0;
while (rolling)
{
int rolledint = Random.Range(1,10);
if (rolledint != oldInt)
{
Debug.log("Rolled: " + rolledint);
}
}
Hi @chanfort
My solution was to make an array of the “valid numbers”, and always ask a random for the position in that array.
Check this code:
private static List<int> Generate(List<int> initialNumbers)
{
List<int> generatedNumbers = new List<int>();
Random rnd = new Random(DateTime.Now.Millisecond);
int position, nextNumber;
while (initialNumbers.Count > 0)
{
position = rnd.Next(initialNumbers.Count());
nextNumber = initialNumbers.ElementAt(position);
generatedNumbers.Add(nextNumber);
initialNumbers.Remove(nextNumber);
}
return generatedNumbers;
}
The function gets an array of the “valid numbers” and return and array “shuffled”.
This has been already used and tested with 1000 numbers.