[英]Random numbers in Unity C#
Here is my code:这是我的代码:
public class RandomNumbers : MonoBehaviour {
public Transform mCanvas;
public Text[] numbers;
int idx = 0;
void Start()
{
StartCoroutine("CreateNum");
}
IEnumerator CreateNum()
{
while (idx < numbers.Length)
{
Text g = Instantiate(numbers[idx], new Vector3(Random.Range(-100, 100), Random.Range(-100, 100), 0), Quaternion.identity);
g.transform.SetParent(mCanvas, false);
yield return new WaitForSeconds(2f);
Destroy(g);
++idx;
}
}
}
This code makes 4 texts appear in ascending order on the screen.此代码使 4 个文本按升序出现在屏幕上。 I want these four numbers to appear not in increasing but random form.
我希望这四个数字不是以递增的形式出现,而是以随机的形式出现。
What you need to do is shuffle the array of numbers
so they are in a random order, then you can grab in order the randomized list and it acts the same as picking items at random without duplicating.您需要做的是打乱
numbers
数组,使它们按随机顺序排列,然后您可以按顺序抓取随机列表,它的作用与随机选择项目相同,无需重复。
public class RandomNumbers : MonoBehaviour {
public Transform mCanvas;
public Text[] numbers;
int idx = 0;
void Start()
{
//Randomizes the list of numbers
Shuffle(numbers);
StartCoroutine("CreateNum");
}
IEnumerator CreateNum()
{
while (idx < numbers.Length)
{
Text g = Instantiate(numbers[idx], new Vector3(Random.Range(-100, 100), Random.Range(-100, 100), 0), Quaternion.identity);
g.transform.SetParent(mCanvas, false);
yield return new WaitForSeconds(2f);
Destroy(g);
++idx;
}
}
//This is called a Fisher-Yates shuffle https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
//This function can be used with any Array or List you send it.
private static void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = Random.Range(0, n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.