Search Unity

Illegal Characters in Path with SerializeField TextAsset?

Discussion in 'Scripting' started by envysion, Jan 19, 2020.

  1. envysion

    envysion

    Joined:
    Apr 2, 2017
    Posts:
    3
    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:

    Code (CSharp):
    1.  
    2. public class Randomizer : MonoBehaviour
    3. {
    4.     public TextMeshProUGUI workoutText;
    5.     private List<string> workoutList;
    6.     [SerializeField] private string formattedText;
    7.     [SerializeField] private TextAsset workoutTextAsset;
    8.    
    9.     void Awake()
    10.     {
    11.         string workoutsFile = workoutTextAsset.ToString(); //I've tried workoutTextAsset.text as well. Same error.
    12.         workoutList = ReadWorkouts(workoutsFile);
    13.     }
    14.  
    15.     public List<string> ReadWorkouts(string workoutsFile)
    16.     {
    17.         List<string> fileDataList = new List<string>();
    18.         using (StreamReader sr = new StreamReader(workoutsFile))
    19.         {
    20.             string line;
    21.             while ((line = sr.ReadLine()) != null)
    22.             {
    23.                 fileDataList.Add(line);
    24.             }
    25.         }
    26.         return fileDataList;
    27.     }
    28.    
    29.     public void RandomWorkout()
    30.     {
    31.         formattedText = workoutList[Random.Range(0, workoutList.Count)];
    32.         formattedText = formattedText.Replace("\\n", "\n");
    33.         workoutText.SetText(formattedText);
    34.     }
    35. }
    36.  
    Here is my stacktrace:
    stacktrace.PNG

    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!
     
  2. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    357
    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:
    Code (CSharp):
    1. var filesArray = workoutTextAsset.text.Split('\n');
    2. var fileDataList = new List<string>(filesArray);
     
    envysion likes this.
  3. envysion

    envysion

    Joined:
    Apr 2, 2017
    Posts:
    3
    Ohhh, I see. Thank you, I overlooked that!
     
    grizzly likes this.