- Home /
How do I read a text file using Resources.Load?
I have a folder in Assets named Wave_Position that has text files with data separated by line breaks. I have a folder in Assets named Resources that has text files with the same data separated by commas. My code is working when I try to read my text files using File.ReadAllLines().
public List<string> lines;
public string myFile;
public Color color;
public Renderer rend;
string filePath, fileName;
// Start is called before the first frame update
void Start()
{
fileName = $"Wave_Position_{4*transform.position.x}_{4*transform.position.y}_{4*transform.position.z}.txt";
filePath = Application.dataPath + "/Wave_Position/" + fileName;
// myFile = Resources.Load<TextAsset>(fileName).text;
// lines = myFile.Split(',');
lines = File.ReadAllLines(filePath).ToList();
}
My code is not working when I try to read the text files using Resources.Load. Note that I also changed lines from a List of string to a string[].
public string[] lines;
public string myFile;
public Color color;
public Renderer rend;
string filePath, fileName;
// Start is called before the first frame update
void Start()
{
fileName = $"Wave_Position_{4*transform.position.x}_{4*transform.position.y}_{4*transform.position.z}.txt";
// filePath = Application.dataPath + "/Wave_Position/" + fileName;
myFile = Resources.Load<TextAsset>(fileName).text;
lines = myFile.Split(',');
// lines = File.ReadAllLines(filePath).ToList();
}
How can I make my program read the text files using Resources.Load and split the data by line or comma (depending on which folder I go to)?
Answer by davidcox70 · Aug 06, 2020 at 10:35 PM
I think with Resources.Load, you do not use the extension (.txt in this case). Just use the rest of the filename without the .txt.
And I don't think you need the .text on the end of the Resources.Load line.
lines = myFile.Split(','); seems like the correct way to split comma separated data.
I did need the .text on the end of the Resources.Load line, but taking out the .txt solved my problem. Thank you!
Answer by Fredjack99 · Oct 26, 2021 at 10:31 PM
I was having trouble loading my resource files as TextAsset until I discovered that unity only loads text for certain file extensions. In my case I was trying to use '.yml' but unity only reads '.yaml'
Full details here: https://docs.unity3d.com/Manual/class-TextAsset.html
Your answer
Follow this Question
Related Questions
Loading Resources in a Native Plugin 0 Answers
Instanciate gameobject from Resources subfolder 1 Answer
Interact with objects from Resources.Load 3 Answers
[solved]Using WWW instead of resources.load causes hang 1 Answer
Performance of Resources.Load vs Direct Reference vs Resources.LoadAsync for large level assets 1 Answer