Search Unity

2D list of gameobjects - array, generic list, or whatever

Discussion in 'Scripting' started by Ghidera, Feb 17, 2015.

  1. Ghidera

    Ghidera

    Joined:
    Mar 6, 2013
    Posts:
    53
    I'd been trying all afternoon to figure out how to create and use some form of 2D array so I can organize four columns of gameobjects and refer to them by numeric indexes. I just can't seem to get there.

    I tried a list of lists but I always get null pointer errors when trying to populate the lists

    List<List<GameObject>> CardColumns = new List<List<GameObject>>();
    List<GameObject> Column1 = new List<GameObject>();
    List<GameObject> Column2 = new List<GameObject>();
    List<GameObject> Column3 = new List<GameObject>();
    List<GameObject> Column4 = new List<GameObject>();

    in Start()

    CardColumns.Add(Column1);
    CardColumns.Add(Column2);
    CardColumns.Add(Column3);
    CardColumns.Add(Column4);

    Later in a function
    CardColumns[0].Add(newGO);

    Which tosses an argument out of range error.

    I've also tried it with an array of lists and messed with regular arrays but got nowhere. Obviously I'm missing something pretty basic. What is it?
     
  2. bloomingdedalus

    bloomingdedalus

    Joined:
    Aug 13, 2012
    Posts:
    139
    Looks fine to me - you should make sure if you're instantiating something that you're not getting a null gameobject. Sometimes it's hard to ensure you actually got the game object - usually I stick with storing the transform instead in arrays.

    What's your method for procuring the game object you're trying to store?
     
  3. Ghidera

    Ghidera

    Joined:
    Mar 6, 2013
    Posts:
    53
    I'm instantiating a prefab UI Image. After instantiating I get its recttransform and change the anchorposition and when I check the object is good.

    What I have figured out is that CardColumns.Add(ColumnX) doesn't do anything. CardColumns.Count reports 0 elements right after adding the four columns.
     
  4. Ghidera

    Ghidera

    Joined:
    Mar 6, 2013
    Posts:
    53
    Never mind, I just figured it out. It looked like a scope problem because the lists worked in Start() but were null inside a function. While I was staring at the debug output it finally dawned on me that the function debugs were appearing before the ones in start... I'd been calling the functions from start BEFORE the list/array work.

    Definitely a DOH!
     
    Last edited: Feb 17, 2015
  5. DeveshPandey

    DeveshPandey

    Joined:
    Sep 30, 2012
    Posts:
    221