Search code examples
c#unity-game-engine2d-games

How can I use a resource text file with File.ReadAllLines?


I've got a file with some names of files in it for loading prefabs. I was loading the files with File.ReadAllLines(hardPathToFile) but that doesn't work when you build. You need to use a "Resource" folder. So I tried using Resource.Load(fileName) however that doesn't bring out a list or array. I then tried File.ReadAllLines(Resource.Load(fileName, typeOf(TextAsset)) as TextAsset)) but that doesn't work because the resource that gets loaded isn't a string filepath.

Here's the full code:

void getList(string filePath)
{
    prefabObjects.Clear();
    //Read all the lines from the file. File loaded from resources

    print((Resources.Load(filePath, typeof(TextAsset)) as TextAsset).text);

    var prefabs = File.ReadAllLines((Resources.Load(filePath, typeof(TextAsset)) as TextAsset).text);
    print(prefabs);
    foreach (var prefab in prefabs)
    {
        print(prefab);
        GameObject newPrefab = Resources.Load(prefab, typeof(GameObject)) as GameObject;
        prefabObjects.Add(newPrefab);
    }
}

How can I get this to work?

All help appreciated, thanks :)


Solution

  • If you previously used a hard path to the file, I'm guessing you did something like /path/to/file.txt. With Resources.Load() you don't specify the file endings (file.txt -> file).

    Here's what I did in my project to read the contents of a textfile:

    var api = Resources.Load("ConnectionString") as TextAsset;
    var apiKey = api.text;