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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM