2

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 :)

crabcrabcam
  • 219
  • 1
  • 3
  • 15

1 Answers1

2

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;
Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32
  • 1
    would the `apiKey` variable be able to be split into a list with something like `File.ReadAllLines()` or is it just a string? – crabcrabcam Jan 27 '17 at 11:56
  • 1
    It would be the entire contents: https://docs.unity3d.com/ScriptReference/TextAsset-text.html It would be possible to use .Split() on this, for instance on newlines: http://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net – Fredrik Schön Jan 27 '17 at 11:59
  • 1
    I've managed to get it working with `.Split()` Thanks :) – crabcrabcam Jan 27 '17 at 12:10