- Home /
GUI.DrawTexture C#
So I have this line of code:
void OnGUI(){
GUI.color = new Color (1, 1, 1, alpha);
GUI.depth = drawDepth;
GUI.DrawTexture (new Rect (10, 10, 10, 10), fadeTexture, ScaleMode.StretchToFill, true);
}
But, when ever the function happens, I get this error:
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, ScaleMode scaleMode, Boolean alphaBlend) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:189) FadeOutWhiteC.OnGUI () (at Assets/Custom Assets/Scripts/FadeOutWhiteC.cs:28) FadeOutWhiteC.Update () (at Assets/Custom Assets/Scripts/FadeOutWhiteC.cs:16)
What must I do to avoid this error?
Answer by Burla · Apr 18, 2014 at 09:40 PM
In the code you provided you didn't declare fadeTexture ? I guess you need this code at the top of your script.
Public Texture fadeTexture;
And then you should drag and drop the texture into the field in the editor.
Let me know if this helped.
Well that wasn't the whole code. Earlier in the script I declared the texture. Here's the whole code:
using UnityEngine;
using System.Collections;
public class FadeOutWhiteC : $$anonymous$$onoBehaviour {
public Texture2D fadeTexture;
public float fadeSpeed = 0.2f;
public int drawDepth = -1000;
public GameObject door;
private float alpha = 0.0f;
private int fadeDir = -1;
void Update(){
if (door == null)
OnGUI ();
}
void OnGUI(){
alpha -= fadeDir * fadeSpeed * Time.deltaTime;
alpha = $$anonymous$$athf.Clamp01 (alpha);
GUI.color = new Color (1, 1, 1, alpha);
GUI.depth = drawDepth;
GUI.DrawTexture(new Rect(10, 10, 10, 10), fadeTexture, Scale$$anonymous$$ode.StretchToFill, true);
}
}
Answer by Bunny83 · Apr 19, 2014 at 02:40 PM
From your call stack of your error (and additionally from your comment) we can see that you call OnGUI manually from Update. This will break the whole GUI stuff. You never call OnGUI manually, it's called automatically by unity, so remove the call from Update.
Also like Burla said, make sure you assigned a texture to the variable in the inspector.