C# 2D Generic List

979 views Asked by At

I'm working on a talents/skills tree system for my game made with Unity and I've got a class for my 45 talents buttons that looks like this:

public class SaveTalentClass {
    public int talId;
    public int talCurRank;
    public int talMaxRank;

    public SaveTalentClass(int id, int cRank, int mRank)
    {
        talId = id;
        talCurRank = cRank;
        talMaxRank = mRank;
    }
}

I created 10 "Talent Lists" so the player can save different talents and I stored these 10 Lists in another List for easier access. So I've created a 2D list like that:

public List<List<SaveTalentClass>> containerList = new List<List<SaveTalentClass>>();

And added the 10 "talent Lists" into it but now I'm stuck trying to access/write in this 2D List.

I've tried a test like:

containerList[0][0].Add (new SaveTalentClass(0,1,2));

but got an error: SaveTalentClass' does not contain a definition forAdd' and no extension method Add' of typeSaveTalentClass' could be found (are you missing a using directive or an assembly reference?)

I'm pretty sure there's an easy fix for that but I couldn't figure out how to do it !

Thanks for helping me :)

2

There are 2 answers

1
Felipe Oriani On BEST ANSWER

Since you have the containerList, you can add an object of the type on it, in that case is a List of Lists. So, add a new list of SaveTalentClass and after you can access it by 0 index to add an object of SaveTalentClass object, for sample:

// add the first list in the containerList
containerList.Add(new List<SaveTalentClass>());

// add an item in the first list of containerList
containerList[0].Add(new SaveTalentClass(0,1,2));
0
LInsoDeTeh On

Giving two indexes, you're already inside the second list. Either, if you want to add a new element to one of the lists inside the outer list, use

containerList[0].Add (new SaveTalentClass(0,1,2));

Or if you want to modify an existing one:

containerList[0][0] = new SaveTalentClass(0,1,2);