Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

[SOLVED] How to handle Resources.Load file not found NullReferenceException

Discussion in 'Getting Started' started by jshrek, Mar 30, 2015.

  1. jshrek

    jshrek

    Joined:
    Mar 30, 2013
    Posts:
    220
    So I have the following code which works fine when the text file is present:
    Code (CSharp):
    1. TextAsset localTextFile = (TextAsset)Resources.Load("MyTextFile", typeof(TextAsset)); //MyTextFile.txt is present in Assets/Resources folder
    2.    
    3. if (string.IsNullOrEmpty(localTextFile.text)) {
    4.     Debug.Log("Error: file empty or null\n");
    5. } else {
    6.     Debug.Log(localTextFile.text);
    7. }
    When the file is present, it succesfully goes to Debug.Log(localTextFile.text); line.

    Now if I change MyTextFile to a non-existent filename, instead of getting the Debug.Log("Error: file empty or null\n"); line, I get the following error:

    NullReferenceException: Object reference not set to an instance of an object

    How can I handle this NullReferenceException properly?
     
  2. nicecapj

    nicecapj

    Joined:
    Sep 24, 2013
    Posts:
    1
    If the relevant data, and ends the program, otherwise to be ignored in the logic.

    if(localTextFile != null)
    {
    ProcessLogic(localTextFile );
    }
     
  3. jshrek

    jshrek

    Joined:
    Mar 30, 2013
    Posts:
    220
    @nicecapj Thank you, this helped me understand the problem.

    You cannot use string.IsNullOrEmpty to test either localTextFile.text or localTextFile.

    But you can test localTestFile against null. So my corrected code is:

    Code (CSharp):
    1. TextAsset localTextFile = (TextAsset)Resources.Load("MyTextFile", typeof(TextAsset)); //MyTextFile.txt is present in Assets/Resources folder
    2.      
    3. if (localTextFile == null) {
    4.     Debug.Log("Error: file null or missing\n");
    5. } else {
    6.     Debug.Log(localTextFile.text);
    7. }