我在為我在 Unity 中制作的游戲編程此功能時遇到問題。我使用 SortedList<GameObject, float> 來存盤我的玩家進入觸發器的可互動物件,以及它們與他的距離。我希望他只能與一個物件互動,即最接近他的物件。出于這個原因,我遍歷串列并使用每幀的新距離更新鍵的浮點值,然后將物件的 canInteract bool 設定為 true,如果它位于串列的索引 0 中,則表示最接近玩家.
這可行,但 Unity 向我拋出一個錯誤,說我正在更改值,而它仍在迭代 KeyValue 對,如下面的螢屏截圖所示。

我的代碼如下:
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 或者這是否可以解決問題,因為在遍歷串列時我仍然需要更改值
uj5u.com熱心網友回復:
好吧,在查看了評論之后,我意識到在這種情況下使用 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] 中的游戲物件,如果是,我將 canInteract bool 設定為 true。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/463238.html
上一篇:從Sharepoint串列中讀取時使用where子句的Foreach
下一篇:獲取列舉的ToString方法
