0

I'm working in Unity 4.3.3f1 and I'm trying to load a Texture at runtime but I keep getting NullReferenceExpection. I have my .png located in Asset/Resources as specified by this question.

My actual code is

  Texture tex = Resources.Load("lava_pic", typeof(Texture)) as Texture;
  Rect pos = new Rect(transform.position.x - 50, 
        transform.position.y - 50, 100, 100);

  GUI.DrawTexture(pos, tex);

I've also tried with the .png extension

The Error is

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUI.DrawTexture (Rect position, UnityEngine.Texture image, ScaleMode  
  scaleMode, Boolean alphaBlend, Single imageAspect) (at     
C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:208)
UnityEngine.GUI.DrawTexture (Rect position, UnityEngine.Texture image) (at 
 C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:204)
LavaScript.FixedUpdate () (at Assets/Scripts/LavaScript.cs:35)'

If I put in a Debug.Log(tex); it also prints out null so that is where the problem is.

I really don't know why this is occurring. It's in a Resources folder since that's where it needs to be and I'm fairly certain it can be a .png file. What am I doing wrong?

2 Answers 2

3

Try removing the file extension so it's just lava_pic.

Relevant info from the Resources docs:

...extensions must be omitted

Update

Working example from my machine. It's possible if your original code is located outside of OnGUI that the null object is GUI and not the texture.

My texture is located at Assets/Resources/galaxy_example.png

public class DrawTexture : MonoBehaviour {
Texture tex;
Rect pos;
void Start () {
    tex = Resources.Load("galaxy_example", typeof(Texture)) as Texture;
    pos = new Rect(transform.position.x - 50, 
                   transform.position.y - 50, 100, 100);
}
void OnGUI(){
    Debug.Log (tex);
    GUI.DrawTexture(pos, tex);
}
}
Sign up to request clarification or add additional context in comments.

3 Comments

Tried, same result :/
@Daniel Where are you calling this code from? See my update in case you are testing you code outside of OnGUI
Behavior script for a prefab, FixedUpdate(). The script is inheriting from Monobehavior
1

If you are trying to load a image inside the Asset/Resource folder use: Resoure.Load("image",typeof(texture)) as texture.

If you want to load a image from other folder load full path: Texture2D Txt= Resources.LoadAssetAtPath<Texture2D> ("Assets/Sprites/Scene1.png");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.