method problem

I’m trying to create a method that puts a txt.file in an array.
But I’m doing something wrong. I get no array back. What am I doing wrong?

    public string[] ImportTextFile(string textFile)
    {
        string[] DialogueStrings;
        TextAsset TextFileToLoad = (TextAsset)Resources.Load(textFile);

        if (TextFileToLoad != null)
        {
            DialogueStrings = new string[1];                                        
            DialogueStrings = (TextFileToLoad.text.Split('

'));
}
return DialogueStrings;
}

I would point ask a few questions from your code:

  1. Why are you instancing the “string DialogueStrings” array before the condition “if (TextFileToLoad != null)”? It’s unneccasary if the condition returns false.

  2. Why are you initializing the “DialogueStrings” array to only have 2 elements? Arrays in C# are 0 based, so “= new arraytype[1]” allocates 2 instances of that type in memory, index 0 and 1. You aren’t allowing for scenarios where there are more than two lines of dialogue. You don’t even need to initialize the array to a defined number either, so long as the “Split” method returns a string.

  3. You have no plan for “if (TextFileToLoad != null)” returning false at the moment. This might be why you are not returning anything. It could be that your TextFileToLoad is not loading because of an incorrect file path.

I would consider the following:

     public string[] ReadDialogueFromFile(string dialogueFilePath)
     {
         TextAsset dialogueFile = (TextAsset)Resources.Load(dialogueFilePath);
 
         if (dialogueFileToLoad != null)
         {
		string[] dialogueStrings = (dialogueFile.text.Split('

'));
return dialogueStrings;
}
else
{
Debug.Log("No fialogue file found at specified file path - " + dialogueFilePath);
return null;
}
}