zoukankan      html  css  js  c++  java
  • Unity 产生各不相同的随机数

    1. 网上很多方法都说用时间种子来解决,但是在极短的时间内,这种方法没效

    Random r = new Random(DateTime.Now.Millisecond);
     
    Random Counter = new Random(unchecked((int)(DateTime.Now.Ticks >> ctr)));
     
    Random Counter = new Random(System.Guid.NewGuid().GetHashCode());

    2. 用Random结合Hashtable才完美实现我想要的效果

        以下是随机生成3个小于3的各不相同正整随机数的代码,生成的结果是0 1 2, 2 0 1等,而不会出现像 0 0 1 这样有重复数的情况

    string testStr;
        void OnGUI()
        {
            if (GUILayout.Button("产生随机数"))
            {
                testStr = "";
     
                Hashtable hashtable = new Hashtable();
                System.Random rm = new System.Random();
                int RmNum = 3;
                for (int i = 0; hashtable.Count < RmNum; i++)
                {
                    int nValue = rm.Next(3);
                    if (!hashtable.ContainsValue(nValue))
                    {
                        hashtable.Add(nValue, nValue);    //Add(key,value)
                        testStr += nValue + " ";
                    }
                }
            }
            GUILayout.Label(testStr);
        }
  • 相关阅读:
    C# 5注释
    C# 4关键字
    C# 3练习题
    python之子类调用父类的同名属性和方法
    python之继承
    python之对象删除和输出
    python之r,w,a
    python之类中的方法和属性
    python之面向对象
    python之os对文件的操作
  • 原文地址:https://www.cnblogs.com/dabiaoge/p/4158934.html
Copyright © 2011-2022 走看看