Search code examples
c#androidunity-game-engineresourcesassets

Unity: Resources.Load is not working


string filePath = "hfba_25";
TextAsset textAsset = Resources.Load(filePath) as TextAsset;
string fileString = textAsset.text;

I cant seem to figure it out why the resources wont load not in the editor and also not on a android device? The file hfba_25 is in the folder Assets > Resources > hfba_25

Edit_1: textAsset is always returned as NULL


Solution

  • If textAsset is always null, it can mean two things (due to your code):

    1. The file hfba_25 doesn't exist in the Resources subdir;
    2. The file does exist, but can't be cast as a TextAsset.

    To check which of the two is true, you need to change the code to this:

    TextAsset textAsset = (TextAsset)Resources.Load(filePath);
    Debug.Log(textAsset);
    

    then run inside Unity and check the console.

    If you just get Null, then it means that it's 1 (file doesn't exist).

    If instead you get InvalidCastException: Specified cast is not valid., then it means it's 2, the file exists but it can't be cast as a TextAsset type.

    This happens because in C#, if you cast using the keyword as, when the cast is invalid you don't get an exception, but instead the reference is just set to null.