簡體   English   中英

如何使用列表中的值而不重復? (隨機范圍)

[英]How to use value from list without repeating? (Random.Range)

我有一個清單(planePosition)。 我想隨機使用那些列表值而不重復,所以我正在使用

 for( int a=0; a< planePosition.Count; a++)
    { 
    int r=Random.Range(0,planePosition.Count);
    Newplan.transform.position =  new Vector3 (planePosition[r].x, planePosition[r].y ,9.990011f);
    planePosition.RemoveAt(r);
    }

但我仍然得到重復的價值。

做就是了

readonly Random _random= new Random(); 


for( int a=0; a< planePosition.Count; a++)
{ 
int r= _random.Range(0,planePosition.Count);
Newplan.transform.position =  new Vector3 (planePosition[r].x, planePosition[r].y ,9.990011f);
planePosition.RemoveAt(r);
}

沒有隨機函數可以保證一個值不會重復兩次。 這就是為什么它是隨機的。 這意味着如果您依靠它,代碼將很脆弱。

相反,您可以保留一個集合來跟蹤使用的ID

List<int> usedIndexes = new List<int>();

然后有一種獲取非重復索引的方法:

private int GetRandomInt(int min, int max)
{
     int num = Random.Range(min, max);

     while(usedIndexes.Contains(num))
     {
          num = Random.Range(min, max);
     }

     return num;
}

由於我目前的聲譽,我無法發表評論。 請不要以為答案。

我有一些疑問:

1)參見juharr的評論。

2)在這里,您總是(另一個)設置相同的字段/屬性:

Newplan.transform.position =  new Vector3 (planePosition[r].x, planePosition[r].y ,9.990011f);

那是您想要的行為嗎?

3)我認為,通過從列表中刪除您使用的值,您可以確保不再使用它。 這與隨機無關。 如果您始終采用列表的第一個值,那么這也應該起作用。 但是:您確定列表中的值是唯一的嗎? 也許您的問題不在該方法中。 相反,它是提供planePosition-list的方法。

我得到了我的答案:)

for(int a=0; a<16; a++)
        {


            //rnd = new Random ();
            while (planePosition.Count != 0)
            {
                     int index = Random.Range (0, planePosition.Count-1);
                     randomizedList.Add (planePosition [index]);
                    Newplan.transform.position =  new Vector3 (randomizedList[r].x, randomizedList[r].y ,9.990011f);
                    planePosition.RemoveAt (index);

            }

        }
  private void ScoreRandomize()
    {
        List<int> listRnd = new List<int>();
        listRnd.AddRange(scoreAmount); //scoreAmount is array or list with orginal data
        for (int i = 0; i < listRnd.Count + i; i++)
        {
            int rnd = UnityEngine.Random.Range(0, listRnd.Count);
            scoreDisplayTxts[i].text = listRnd[rnd].ToString();
            scoreAmount[i] = listRnd[rnd];
            listRnd.RemoveAt(rnd);
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM