簡體   English   中英

ArgumentException: 字典中已存在具有相同鍵的元素

[英]ArgumentException: An element with the same key already exists in the dictionary

在我的項目中,我有兩個場景 'Opening' 'Main'。

如果有一段時間沒有輸入或完成任務,
它將回到開場場景並可以重新開始。

它的工作原理,去打開場景 - >主場景
並轉到主場景 -> 開場場景

然而,“主場景 -> 開場場景”,當我再次嘗試進入主場景時,
它顯示這些錯誤。

ArgumentException: An element with the same key already exists in the dictionary.
System.Collections.Generic.Dictionary`2[System.Int32,System.Collections.Generic.Dictionary`2[KeyDelayData+Delay,UnityEngine.Sprite]].Add (Int32 key, System.Collections.Generic.Dictionary`2 value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404)
Note.Init () (at Assets/Scripts/Music/Note.cs:22)
ManagerChat.Awake () (at Assets/Scripts/Chatting/ManagerChat.cs:315)

ArgumentException: An element with the same key already exists in the dictionary.
System.Collections.Generic.Dictionary`2[System.Int32,UnityEngine.AudioClip].Add (Int32 key, UnityEngine.AudioClip value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404)
SoundManager.Awake () (at Assets/Scripts/Music/SoundManager.cs:16)

對我來說看起來像是一些重置變量問題,但我不知道這是什么意思
我能做些什么來解決這個問題?

您正在嘗試將現有鍵添加到Dictionary

315ManagerChat腳本中的Awake函數中的第一個錯誤。

16SoundManager腳本中的Awake函數中的第二個錯誤。

解決方法:

1 . Dictionary.Clear()應該這樣做,但如果你不想清除它們,然后檢查鑰匙是否已在Dictionary與添加它之前Dictionary.Add功能:

假設這是您的代碼:

Dictionary<int, Sprite> imageDict = new Dictionary<int, Sprite>();
int keyToAdd = 1;
imageDict.Add(keyToAdd, new Sprite());

將其更改為:

Dictionary<int, Sprite> imageDict = new Dictionary<int, Sprite>();
int keyToAdd = 1;
//Add only if key does not exist
if (!imageDict.ContainsKey(keyToAdd))
{
    imageDict.Add(keyToAdd, new Sprite());
}

2 .另一種方法是使用索引( [] )作為更改它的鍵。 涉及Dictionary.Add功能。

Dictionary<int, Sprite> imageDict = new Dictionary<int, Sprite>();
int keyToAdd = 1;
imageDict.Add(keyToAdd, new Sprite());

應該是:

Dictionary<int, Sprite> imageDict = new Dictionary<int, Sprite>();
int keyToAdd = 1;
imageDict[keyToAdd] = new Sprite();

我通過使用 DictionaryValue.Clear (); 修復了這兩個問題。

這是關於我認為的剩余對象和精靈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM