Reputation: 2515
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?
Upvotes: 0
Views: 4531
Reputation: 428
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");
Upvotes: 1
Reputation: 4056
Try removing the file extension so it's just lava_pic
.
Relevant info from the Resources
docs:
...extensions must be omitted
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);
}
}
Upvotes: 3