Search Unity

Resources.Load always returning null?

Discussion in 'Scripting' started by randomJoe1, Aug 15, 2017.

  1. randomJoe1

    randomJoe1

    Joined:
    Jul 17, 2017
    Posts:
    3
    Code (CSharp):
    1.     TextAsset textAsset = new TextAsset();
    2.     textAsset = Resources.Load("hfba_25") as TextAsset;
    3.     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: I am also getting no errors except for a null reference when i try to access textAsset
     
  2. rcenzo

    rcenzo

    Joined:
    Aug 21, 2014
    Posts:
    13
    Are you sure the file type of your hfba_25 file is recognised in Unity as a TextAsset, when you browse towards it in the Project view? This can be of any of the extensions mentioned here: https://docs.unity3d.com/Manual/class-TextAsset.html

    You are correct in not using the extension in the call to Resources.Load, but I then expect Unity not to recognise it as a TextAsset to begin with.
     
  3. Dave-Carlile

    Dave-Carlile

    Joined:
    Sep 16, 2012
    Posts:
    961
    First thing, you don't need to allocate the text asset first. Resources.Load is allocating and returning an instance.
    1. TextAsset textAsset = new TextAsset();
    Next, try this to see if it's able to actually find the resource.

    Code (csharp):
    1. Object asset = Resources.Load("hfba_25");
    In other words, remove the "as TextAsset" and just return an Object instance. If *asset* is still null then Unity isn't finding a resource with that name. In that case, triple check to make sure you're spelling it right, make sure the case matches, and so on.

    If it does return an object, then the "as TextAsset" is causing the problem. The *as* syntax does a type cast. It will return null if the object can't be cast to the requested type. So in this case the object is found, but it can't be cast to a TextAsset. As @rcenzo said, make sure your asset is actually one that can be used as a text asset.

    Edit: Another question - when you say the asset is in "Assets\Resources", you added it there in the Unity editor correct? You didn't just drop it into the folder outside of Unity?
     
  4. randomJoe1

    randomJoe1

    Joined:
    Jul 17, 2017
    Posts:
    3
    Yup, you are right. The json files are saving as Type:File in windows and not as Type:json. Thanks man/woman.