Search Unity

Resolved adding entries to a nested list?

Discussion in 'Scripting' started by Monsterwald, May 25, 2022.

  1. Monsterwald

    Monsterwald

    Joined:
    Jan 19, 2020
    Posts:
    68
    I've created a little script which contains a few strings.

    Code (CSharp):
    1. [System.Serializable]
    2. public class TaskData
    3. {
    4.     public string description;
    5.     public string date;
    6. }
    and in another script I added this line:

    public List<TaskData> tasks = new List<TaskData>();


    Which allows me to do this:


    The problem: I like to add those elements via script, whenever I press a button ingame.... and somehow, I don't really know how.

    I tried this: --but I get out of range errors

    Code (CSharp):
    1.     public void AddText() //triggered via button press
    2.     {
    3.        ID++;
    4.        tasks.Add(tasks[ID]);
    5.  
    6.        tasks[tasks[ID].description = inputField.text;
    7.        tasks[tasks[ID].description = date.ToString();
    8.     }
    9.  
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    The code as posted here wouldn't compile, so it wouldn't have a chance to give you an out of range error. Lines 6 and 7 have nonsense brackets. I'll assume those lines are a newer test/addition or a mistake copying into the forums, and focus on line 4 where you would actually get that error.

    Imagine yourself as the computer coming across line 4 here. Before it can call tasks.Add, it needs to resolve the parameters so it knows what to send to tasks.Add. So that means it will attempt to retrieve tasks[ID], when you have just added to ID and made it 1 larger than the list's current size - that is, out of range.

    The way to do this is to create a new TaskData object and then add that item to the list. You probably don't need the ID variable at all.
    Code (csharp):
    1. var newlyCreatedTask = new TaskData();
    2. newlyCreatedTask.description = inputField.text;
    3. tasks.Add(newlyCreatedTask);
     
    Bunny83 and Monsterwald like this.
  3. Monsterwald

    Monsterwald

    Joined:
    Jan 19, 2020
    Posts:
    68
    @StarManta thanks a bunch, was simpler as thought and yea, I copy/pasted my script but I had some layout issues, so my tired self wrote it a bit messy & wrong.