【问题标题】:How to change order in array ONLY ONCE in unity,monodevelop如何在统一中仅更改一次数组中的顺序,monodevelop
【发布时间】:2020-06-07 17:39:44
【问题描述】:

我有数组 (1,2,3,4,5),我想随机播放数字 f.e(4,3,2,1,5),并在开始时调用 shuffle()。 我写了函数,但它重复相同的数字而不是改变顺序。我的代码在下面;

 public void Shuffle()
    {
        for (int i = 0; i < lists[BrojLevela].Length ; i++)
        {
            int rnd = Random.Range(0, lists[BrojLevela].Length);
            tempGO = lists[BrojLevela][rnd];
            lists[BrojLevela][rnd] = lists[BrojLevela][i];
            lists[BrojLevela][i] = tempGO;
        }
    }

【问题讨论】:

    标签: c# arrays unity3d


    【解决方案1】:

    我刚刚对此进行了测试,它应该可以工作:

    private IList<int> strList = new List<int>();
    void Start()
    {
        strList.Add(1);
        strList.Add(2);
        strList.Add(3);
        strList.Add(4);
        strList.Add(5);
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Shuffle(strList);
    
            foreach(int a in strList)
            {
                Debug.Log(a.ToString());
            }
    
        }
    }
    
    public void Shuffle<T>(IList<T> list)
    {
    
    
        int n = list.Count;
        int rnd = Random.Range(0, n-1);
        while (n > 1)
        {
            n--;
            int k = rnd;
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
    

    【讨论】:

      【解决方案2】:

      Random.Range 是用于生成伪随机数的 Unity 类,但根据某些文档,如果提供相同的范围,实际上会给出可重复的结果。
      如果您将其更改为使用 System.Random 类,那么它对我有用。

      只是改变:

      int rnd = Random.Range(0, lists[BrojLevela].Length);
      

      收件人:

      int rnd = new Random().Next(0, lists[BrojLevela].Length);
      

      这是使代码示例按预期工作的最简单更改,但是,最好在循环之外创建 Random 对象的实例并将其缓存,因为无需每次都创建一个新对象。

      【讨论】:

      • thnx 但 Next 不是随机生成的
      • 这是一个不同的随机。 Unity 有UnityEngine.CoreModule.Random,C# 有System.Random。两者的功能不同,根据您对预期行为的描述,您需要System.Random。如果您在文件顶部添加using System;,您应该可以使用System.Random 版本
      • 我刚刚粘贴了这个 coede 并解释说它不起作用它会返回 (1,2,3,1,3)
      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多