繁体   English   中英

排序列表<key, value> :更改循环内的值时出错,循环遍历列表/Unity,C#</key,>

[英]SortedList<Key, Value>: Error while changing the values inside a loop, while looping through the list / Unity, C#

我在为我在 Unity 中制作的游戏编写此功能时遇到问题。 我使用 SortedList<GameObject, float> 来存储我的玩家输入触发器的可交互对象,以及它们与他的距离。 我希望他只能与离他最近的一个 object 进行交互。 出于这个原因,我遍历列表并用每帧的新距离更新键的浮点值,然后将对象的 canInteract bool 设置为 true,如果它在列表的索引 0 中,意味着最接近玩家.

这行得通,但 Unity 向我抛出一个错误,指出我正在更改值,同时它仍在迭代键值对,如下面的屏幕截图所示。

在此处输入图像描述

我的代码如下:

public SortedList<GameObject, float> interactablesInRange = new SortedList<GameObject, float>();

public void CheckForInteractableDistance()
    {
        foreach (KeyValuePair<GameObject, float> interactable in interactablesInRange)
        {
            interactablesInRange[interactable.Key] = DistanceChecker(gameObject, interactable.Key);
            Debug.Log(interactable.Key + " distance from player: " + interactable.Value);

            if (interactablesInRange.IndexOfValue(interactable.Value) == 0)
            {
                interactable.Key.GetComponent<WeaponPickup>().canInteract = true;
            }
            else
            {
                interactable.Key.GetComponent<WeaponPickup>().canInteract = false;
            }
        }
    }


public float DistanceChecker(GameObject fromObj, GameObject toObj)
    {
        float distance = Vector3.Distance(fromObj.transform.position, toObj.transform.position);

        return distance;
    }

我正试图找到一种方法来避免该错误,同时仍在做同样的事情。 有人建议我也许可以用 LINQ 做到这一点,但我不知道如何使用 LINQ 或者这是否可以解决问题,因为我仍然需要在遍历列表时更改值

好吧,在查看了评论之后,我意识到在这种情况下使用 SortedList 并不是必需的,而且我之前使用它的方式是不正确的。

在网上进行了更多研究后,我在该线程 ( https://answers.unity.com/questions/1408498/sorting-a-list-based-of-a-variable.html ) 中发现了一条评论,它基本上回答了我的问题并在一行代码中使用简单的 LINQ 表达式来完成我想做的事情!

所以案例解决了:如果你想做类似的事情,我会发布下面的代码:


private void SortByDistance()
    {
        foreach (GameObject interactable in interactablesInRange)
        {
            interactable.GetComponent<WeaponPickup>().distanceFromPlayer = DistanceChecker(gameObject, interactable);
        }

        interactablesInRange = interactablesInRange.OrderBy(e => e.GetComponent<WeaponPickup>().distanceFromPlayer).ToList();

    }

之后,如果可交互项是列表索引 [0] 中的 GameObject,我只需检查每个可交互项脚本,如果是,我将 canInteract bool 设置为 true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM