首页 > 代码库 > Unity 产生各不相同的随机数

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 = http://www.mamicode.com/rm.Next(3);                if (!hashtable.ContainsValue(nValue))                {                    hashtable.Add(nValue, nValue);    //Add(key,value)                    testStr += nValue + " ";                }            }        }        GUILayout.Label(testStr);    }

Unity 产生各不相同的随机数