Search code examples
c#listloopsdialoginfinite

C# How to iterate throught all the lists in child's list?


so I've stopped to this problem which solution I can't think of, it currently escapes my mind althought I think I did this same thing on another project, but I lost the files..

Thing is, I'm writting a dialogue system that has one answer line, and up to 3 question lines, each of these question lines, when clicked, have another answer line and can have even more questions to be made.

The goal is to be able to make a dialogue system that can have as much answers and questions in line as you want.

But I don't know how to iterate them all, if it was a fixed number, I could make a for loop for each number of questions, but it not being the case, I'm stuck on it!

The following code is an example of a fixed number of ONE question and its answer and another list of questions:

for(int i = 0; i < dialogGiver.dialogLines.Count; i++)
{
    EditorGUILayout.LabelField("Line " + i, EditorStyles.boldLabel);

    dialogGiver.dialogLines[i].line = EditorGUILayout.TextField("Question", dialogGiver.dialogLines[i].line);
    dialogGiver.dialogLines[i].answer = EditorGUILayout.TextField("Answer", dialogGiver.dialogLines[i].answer);

    for (int e = 0; e < dialogGiver.dialogLines[i].dialogLines.Count; e++)
    {
        EditorGUILayout.LabelField("Line " + i + "/ Line " + e, EditorStyles.boldLabel);
    }
}

So thing is, how do I make that loop look for as much sub-questions and sub-lines as the DialogLine (and the DialogLine childs into that DialogLine) has.

This is the DialogLine class:

public class DialogLine
{
    public string line;
    public string answer;

    /// <summary>
    /// This will enable the dialog giver to continue speaking of the same theme (use for long dialogs!)
    /// </summary>
    public List<DialogLine> dialogLines = new List<DialogLine>();
}

Thanks in advance, I'm willing to learn how should this work!


Solution

  •     public void RecursiveMethod(List<DialogLine> list)
        {
             for(int i = 0; i < list.Count; i++)
             {
                   EditorGUILayout.LabelField("Line " + i, EditorStyles.boldLabel);
    
                   list[i].line = EditorGUILayout.TextField("Question", list[i].line);
                   list[i].answer = EditorGUILayout.TextField("Answer", list[i].answer);
                   RecursiveMethod(list[i].dialogLines);
             }
        }
    

    Made this quite fast. But it should be something like this. It will keep iterating through all childs, till it encounters an empty list ofcourse.

    Goodluck!