EDIT: Restarting Unity solved the problem! ;)

I don't know if Unity and GameObjects have anything to do with this, but I am getting a strange duplicate Key error while scripting in Unity.

static void LoadPartyDataIntoBattle()
    foreach (PartyMemberData partyMemberData in ins.TheParty)
        PartyMember partyMemberToAdd = new PartyMember(partyMemberData);
        GameObject PartyMemberUI = Instantiate(ins.PMBattlePrefab, ins.PartyFrontRow.transform);

        PartyMemberUIDisplay display = PartyMemberUI.GetComponent<PartyMemberUIDisplay>();
        display.Name.GetComponent<Text>().text = partyMemberData.Name;
        display.Level.GetComponent<Text>().text = partyMemberData.Level.ToString();
        display.HPValue.GetComponent<Text>().text = partyMemberData.HP.ToString();
        display.TPValue.GetComponent<Text>().text = partyMemberData.TP.ToString();

        BattleManager.PMLinkDict.Add(partyMemberToAdd, display);

In the line PartyMember partyMemberToAdd = new PartyMember(partyMemberData);, the new keyword should create a different PartyMember on the heap, correct? Yet when I run the debugger, attach it to Unity and play, the second time the foreach loop runs I get a duplicate Key error. For reference, I set the values of ins.TheParty (my list of party members) in the Inspector; there are three partyMembers in TheParty as of now. They have different names, attack, defense, etc. But that doesn't matter, does it? Isn't it the memory location that matters?

I made a test file to mimic the problem I had. It worked fine, no surprises here.

using System;
using System.Collections.Generic;

class Cow { }

class MainClass
    static void Main()
        Dictionary<Cow, object> meDict = new Dictionary<Cow, object>();

        List<Cow> myCows = new List<Cow>()
            new Cow(),
            new Cow()

        foreach (Cow c in myCows)
            meDict.Add(c, new object());

        Console.WriteLine("Yay nothing broke"); // this prints just fine

I feel like I'm overlooking something obvious, but I can't for the life of me figure out what the problem is. Help appreciated!

  • 1
    \$\begingroup\$ If it crops up again, take a look at your PartyMember class and make sure the Equals method isn't overridden with something simple. Since you may be passing in duplicate PartyMemberData into the constructor, the Equals method on PartyMember might tell you that two different objects with the same data are equal. \$\endgroup\$ – MichaelHouse Aug 17 '17 at 22:01

For some odd reason, restarting Unity solved the problem!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.