我想从列表中随机选择两个项目。然后在场景中设置这些项目。问题是,有时它会选择在前一个循环中选择的那个。
如何排除第一个选择?
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;
}
}
}
答案 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 :(得分: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;
}