2个列表中的随机选择 - C#

时间:2017-04-19 20:21:59

标签: c# list unity3d random

我想从列表中随机选择两个项目。然后在场景中设置这些项目。问题是,有时它会选择在前一个循环中选择的那个。

如何排除第一个选择?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BeamManager3 : MonoBehaviour {

public List<GameObject> LargeBeamObject = new List<GameObject>();

void Start () {
   LargeBeamPlayerGenerator();
}

void LargeBeamPlayerGenerator(){
    for (int i = 0; i < 2; i++){
        int randomGameObject = Random.Range(0,4);
        GameObject selectedGameObject = LargeBeamObject[randomGameObject];
        MeshRenderer visible = selectedGameObject.GetComponent<MeshRenderer>();
        visible.enabled = true;
    }
}

}

3 个答案:

答案 0 :(得分:1)

var numberOfRandomSelections = 2;

var randomRenderers = Enumerable.Range(0, LargeBeamObject.Count)
       .OrderBy(i => Random.value)
       .Select(i => LargeBeamObject[i].GetComponent<MeshRenderer>())
       .Take(numberOfRandomSelections);

foreach(var renderer in randomRenderers)
   renderer.enabled = true;

说明:

  1. 为对象列表中的所有索引生成数字
  2. 随机索引
  3. 为每个索引选择网格渲染器
  4. 只使用两个第一个渲染器

答案 1 :(得分:0)

将数据保存到新临时列表中,并从该列表中删除所选元素。

void LargeBeamPlayerGenerator(){
List<GameObject> tempObj = LargeBeamObject;
    for (int i = 0; i < 2; i++){
        int randomGameObject = Random.Range(0,4-i);
        GameObject selectedGameObject = tempObj[randomGameObject];
        MeshRenderer visible = selectedGameObject.GetComponent<MeshRenderer>();
        visible.enabled = true;
        tempObj.RemoveAt(randomGameObject);
    }
}

答案 2 :(得分:0)

int last = -1;
int randomGameObject;
for (int i = 0; i < 2; i++){
    while(randomGameObject = Random.Range(0,4) == last) {}
    last = randomGameObject;
    GameObject selectedGameObject = LargeBeamObject[randomGameObject];
    MeshRenderer visible = selectedGameObject.GetComponent<MeshRenderer>();
    visible.enabled = true;
}