我正在努力从向量三列表中删除向量。我正在尝试在从列表中随机选择的位置生成一个框。然后,我需要从列表中删除该项目,以便两个框不会在同一个位置生成。我已经尝试了删除和删除(使用的矢量(,但没有工作。任何帮助将不胜感激。
void Start()
{
Vector3[] Pos = new Vector3[amount_of_pallet];
for (int i =0; i<=amount_of_pallet-1; i++)
{
Pos[i] = new Vector3(startX, 0.5f, 0f);
startX = startX + pallet.transform.localScale.x;
Debug.Log("pos of box = "+Pos[i]);
Debug.Log("x = "+startX);
}
for (int i=0; i < Pos.Length; i++)
{
Random random = new Random();
int posi = Random.Range(0, Pos.Length);
Vector3 val = Pos[posi];
Instantiate(spawnee, Pos[posi],`Quaternion.identity);`
Pos.RemoveAt(posi);
使用列表并从列表中删除和获取函数
void Start()
{
List<Vector3> contList = new List<Vector3>();
for (int i = 0; i < amount_of_pallet; i++)
{
contList.Add(new Vector3(startX, 0.5f, 0f));
startX = startX + pallet.transform.localScale.x;
}
Random random = new Random();
for (int i = 0; i < contList.Count; i++
{
var index = Random.Range(0, contList.Count);
Vector3 position = RemoveAndGet(contList, index);
Instantiate(spawnee, position, Quaternion.identity);
}
}
public T RemoveAndGet<T>(IList<T> list, int index)
{
lock(list)
{
T value = list[index];
list.RemoveAt(index);
return value;
}
}
另一种解决方案是打乱您的列表并迭代它。像这样:
void Start()
{
List<Vector3> contList = new List<Vector3>();
for (int i = 0; i < amount_of_pallet; i++)
{
contList.Add(new Vector3(startX, 0.5f, 0f));
startX = startX + pallet.transform.localScale.x;
}
Shuffle(contList);
foreach (Vector3 position in contList)
{
Instantiate(spawnee, position, Quaternion.identity);
}
contList.Clear();
}
private System.Random rng = new System.Random();
public void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}