- Home /
How can using a static member (Camera) cause a NullReferenceException?
Greetings,
I was attempting to use OnGUI() to create a healthbar that hovers above my enemy units, and I noticed that whenever I click on the screen, a swathe of NullReferenceException errors shows up on my console. The line causing the error is Camera.current.WorldToScreenPoint(transform.position)
. From my understanding, Camera is a static member of UnityEngine. So the main question here is, how am I getting a null reference error when I'm referencing a static field?
void OnGUI() {
Vector3 pos =
Camera.current.WorldToScreenPoint(transform.position);
pos.y = Screen.height - (pos.y + 1);
GUI.BeginGroup(new Rect(pos.x - 4, pos.y, size.x, size.y));
GUI.Box(new Rect(0,0, size.x, size.y), bgTexture, healthStyle);
float truePercent = rawPercent / 100f;
GUI.BeginGroup(new Rect(0,0, (float)size.x * truePercent, size.y));
GUI.Box(new Rect(0,0, size.x, size.y), healthbarTexture, healthStyle);
GUI.EndGroup();
GUI.EndGroup();
}
If you look a little more closely I think you'll find that it's 'current' that is null not Camera. Camera will never be null.
Answer by CHPedersen · Jan 07, 2015 at 01:00 PM
I answered a question very similar to this a while ago. Please go here and read my reply, as you are probably experiencing the same issue now:
http://answers.unity3d.com/questions/173525/when-is-current-camera-null.html