Illegal Characters in Path with SerializeField TextAsset?

Hey there,

I’m an issue with trying to get a TextAsset loaded into Unity. I’m getting “Illegal Characters In Path” in the console, but I haven’t specified a path anywhere in my code, so I’m not sure what’s illegal. I’m relying on the serialized field to specify what file I’d like to read. My text asset is named “workouts.txt”. I’ve made sure it’s a plain text file.

Here is my code:

public class Randomizer : MonoBehaviour
{
    public TextMeshProUGUI workoutText;
    private List<string> workoutList;
    [SerializeField] private string formattedText;
    [SerializeField] private TextAsset workoutTextAsset;
   
    void Awake()
    {
        string workoutsFile = workoutTextAsset.ToString(); //I've tried workoutTextAsset.text as well. Same error.
        workoutList = ReadWorkouts(workoutsFile);
    }

    public List<string> ReadWorkouts(string workoutsFile)
    {
        List<string> fileDataList = new List<string>();
        using (StreamReader sr = new StreamReader(workoutsFile))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                fileDataList.Add(line);
            }
        }
        return fileDataList;
    }
   
    public void RandomWorkout()
    {
        formattedText = workoutList[Random.Range(0, workoutList.Count)];
        formattedText = formattedText.Replace("\\n", "\n");
        workoutText.SetText(formattedText);
    }
}

Here is my stacktrace:

Note:
My target build is to Android. I’m trying to avoid the pitfall of loading a text file into my project that get compressed into the jar file, so Unity can’t find it via an actual specified path. If you can help me avoid this with another solution, I’d love to hear it.

Thank you!

You’re passing the contents of workoutTextAsset to the StreamReader constructor when it expects a path.

TextAsset.text will return the contents of the file, so StreamReader is not required here.

Try this instead:

var filesArray = workoutTextAsset.text.Split('\n');
var fileDataList = new List<string>(filesArray);
1 Like

Ohhh, I see. Thank you, I overlooked that!

1 Like