1. 網上不少方法都說用時間種子來解決,可是在極短的時間內,這種方法沒效dom
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才完美實現我想要的效果ui
如下是隨機生成3個小於3的各不相同正整隨機數的代碼,生成的結果是0 1 2, 2 0 1等,而不會出現像 0 0 1 這樣有重複數的狀況spa
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); }