Search Unity

Dictionary with Lists : How to add objects to one of the Lists?

Discussion in 'Getting Started' started by drdenner, Dec 4, 2015.

  1. drdenner

    drdenner

    Joined:
    Jun 24, 2014
    Posts:
    32
    Code (CSharp):
    1. public static Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>> ();
    2.  
    3. List<GameObject> poolList = new List<GameObject> ();
    4.         for (int i = 0; i < number; i++) {
    5.             GameObject obj = (GameObject)Instantiate (prefab);
    6.             obj.transform.parent = container.transform;
    7.  
    8.             poolList.Add (obj);          
    9.         }
    10. pool.Add (prefab.name, poolList);
    11.  
    This works fine.
    But how do I add an Object to a List in the Dictionary.
    Fx. The Dictionary looks like this: "Fireball", List<Fireball>
    The list have 10 Fireballs, but how do I add more?

    I tried

    Code (CSharp):
    1. pool [prefab.name].Add (Fireball);
    But that just adds more Dictionaries with the name "Fireball"
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    No it doesn't. pool[prefab.name] looks up the string prefab.name in the pool, and returns a List<GameObject>. Then you call Add on that List, and it adds a new object to it. You haven't created any more dictionaries; you haven't even created any more lists; you've just added to the list already there under that name.
     
  3. drdenner

    drdenner

    Joined:
    Jun 24, 2014
    Posts:
    32
    Hmm then I guess the errors im getting is from something else
     
  4. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    If you are getting errors, please post the errors for us to see. @JoeStrout has answered the question that you asked, rather than helped to solve your problem. An easy mistake to make. You think you know what the problem is, so you've asked for help. It is, however, often better to post the problem and then perhaps add what you think may be the issue.

    EG: I'm trying to [Do Something] and I've decided to use a Dictionary of Lists. This is the code I am using: [insert code using code tags] and I expect it to do [thus and such]. I am, however getting these errors [paste errors which can be copied from the lower panel in the console when selecting the error]. These errors occur when I do [this, that and the other thing]. I think it's because [I'm not successfully adding an entry into my dictionary, or whatever].

    This way, the community knows what you are doing, where you are coming from, what the actual errors are - and can give some best advice. This may even be a suggestion to approach the entire problem from a different angle, or simply help fix a small issue with the otherwise good implementation.
     
    JoeStrout likes this.