在Unity中随机排列数组 [英] Shuffle array in Unity

查看:92
本文介绍了在Unity中随机排列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的 array 变量中的数字进行一次随机播放,所以我从 Start()调用了我的 Shuffle 方法.

I want to shuffle the numbers in my array variable once, so I called my Shuffle method from Start().

然后我尝试从更新访问改组后的数组,但无法这样做.我该如何访问?还有其他方法可以将我的数组洗一次,然后永远使用吗?

I then attempt access the shuffled array from update, but I am unable to do so. How can I access it? Is there any other way to shuffle my array once, then use it forever?

private System.Random _random = new System.Random();
float sec;
float timecount;
float starttime;
void Start () {
    starttime = Time.time;
    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8};
    Shuffle(array);
    foreach (int value in array)
    {
        Debug.Log(value);
    }
}

void Update () {
    //time
    timecount = Time.time - starttime;
    sec = (timecount % 60f);
    if (Mathf.Round(sec) == 3f) {
        //access shuffled array
        Debug.Log(array[3]);  <=====error here
    }
}

//for shuffle number from array
void Shuffle(int[] array){
    int p = array.Length;
    for (int n = p-1; n > 0 ; n--)
    {
        int r = _random.Next(1, n);
        int t = array[r];
        array[r] = array[n];
        array[n] = t;
    }
}

推荐答案

当前,您的数组是在 Start()函数中声明的.这意味着只能从 Start()函数中对其进行访问.如果希望能够同时从 Start() Update()访问该数组,则需要通过全局声明来扩大其范围.例如:

Currently, your array is declared within your Start() function. This means it can only be accessed from within the Start() function. If you want to be able to access the array from both Start() and Update() you need to increase its scope by declaring it globally. For example:

private System.Random _random = new System.Random();
float sec;
float timecount;
float starttime;

//declare array globally
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8};

void Start () 
{
  starttime = Time.time;
  Shuffle(array);
  foreach (int value in array)
  {
      Debug.Log(value);
  }
}

void Update () 
{
    //now you can access array here, because it is declared globally
}

此外,请参阅此MSDN文章有关范围的信息C#.

Additionally, have a look at this MSDN article about scope in C#.

这篇关于在Unity中随机排列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆