本文介绍了如何从C#中的向量3列表中删除向量以保持一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力从向量三的列表中删除向量.我试图在从列表中随机选择的位置生成一个框.然后,我需要从列表中删除该项目,以使两个框不会在同一位置生成.我已经尝试了RemoveAt和Remove(使用的向量),但没有奏效.任何帮助将不胜感激.

I am struggling to remove vectors from a vector three list. I am trying to spawn a box at a position randomly selected from a list. I then need to remove the item from the list so that two boxes don't spawn in the same place. I have tried RemoveAt and Remove(used vector) but non have worked. Any help would be much appreciated.

void Start()
{
Vector3[] Pos = new Vector3[ammount_of_pallet];
for (int i =0; i<=ammount_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);

推荐答案

使用列表并从列表中删除并获取功能

Use list and remove and get func from list

void Start()
{ 
    List<Vector3> contList = new List<Vector3>();
    for (int i = 0; i < ammount_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;
    }
}

另一种解决方案是随机播放列表,然后对其进行遍历.像这样:

Another solution is shuffle your list and just iterate over it. Something like this:

void Start()
{ 
    List<Vector3> contList = new List<Vector3>();
    for (int i = 0; i < ammount_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;  
    }  
}

这篇关于如何从C#中的向量3列表中删除向量以保持一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:46