Hey,
I’ve had this problem for a long time now. I think I know what the problem is, but I don’t know how to solve it.
Here is my problem:
I want that every time I call the Run()
function, a random number ( i
) that has not been used before is debugged.
public List List01 = new List();
void Run()
{
while (List01.Contains(i))
{
i = Random.Range(1, 10);
}
List01.Add(i);
//make something with i like debugging
Debug.Log(i);
}
my research says that the reference of i
does not change and so the index is always overwritten.
Can anyone help me?
thanks!
This is very confused.
are you just trying to generate a list of random order ints between a range of values?
If so why not just create a list of integer values and then randomise the order of the list instead?
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Test : MonoBehaviour
{
public static void Shuffle<T>(IList<T> ts)
{
var count = ts.Count;
var last = count - 1;
for (var i = 0; i < last; ++i)
{
var r = UnityEngine.Random.Range(i, count);
var tmp = ts*;*
ts = ts[r];
ts[r] = tmp;
}
}
public Stack NumberStack;
void Start()
{
var randomNumbers = Enumerable.Range(0, 10)
.ToList();
randomNumbers.Shuffle();
NumberStack = new Stack(randomNumbers);
Debug.Log(NumberStack.Pop());
Debug.Log(NumberStack.Pop());
Debug.Log(NumberStack.Pop());
Debug.Log(NumberStack.Pop());
Debug.Log(NumberStack.Pop());
Debug.Log(NumberStack.Pop());
}
}
Try this.
public List<int> List01 = new List<int>();
// Update is called once per frame
void Start()
{
List01.Add(5);
getNewNumeber(5);
}
int getNewNumeber(int i)
{
int n = 0;
int result;
if (!List01.Contains(i)) // Check if there is an i already
{
result = i; // No. Ok to use.
List01.Add(i);
}
else
{
do
{
n = Random.Range(1, 10); // returns 1:9
} while (List01.Contains(n)); // keep trying to find a number not in the list.
List01.Add(n);
result = n; // New number
}
//make something with i like debugging
Debug.Log(n);
return result;
}