- Home /
Null reference..
I know this quastion is being answered lot of times before, I searched and read lot topics, but none done work for me...
Here is the problem...
I have one class in a separete file that doesen't inheritate from Mono, just store all I need to use in Mono..
Now I have my mono class that is attached to Empty Game object.
This is the simple test, I need to work only OnGUI, everything is going to be 2D.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class test : MonoBehaviour {
proba t = new proba(10,10,100,100); //proba constructor and used for myRect
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(t.myRect.Contains(Event.current.mousePosition)){
if(Event.current.type == EventType.MouseUp){
t.myRect.x = 0;
}
}
}
void OnGUI(){
GUI.Box(t.myRect,"");
}
}
I have that little box on screen with parameters i passed to proba... but the problem is I am getting null reference when I want to click on that box, it doesn't know what is t.myRect.x... Everything in proba class is public, and here it is...
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class proba{
public float x;
public float y;
public float w;
public float h;
public Rect myRect;
public proba(float X,float Y,float W, float H){
x = X;
y = Y;
w = W;
h = H;
myRect = new Rect(x,y,w,h);
}
}
NullReferenceException: Object reference not set to an instance of an object
And it is pointing to line 13 in test witch is begining of if statement where I have same check for Event...
Answer by Bunny83 · Dec 25, 2012 at 08:48 PM
It's quite simple: the Event class will only contain a valid event inside OnGUI. You use it in Update. In Update Event.current will always be null.
So just move your code in your OnGUI function. It's quite funny since you said in your question that you only use OnGUI but you actually use Update.
That was enough... simple... Thx a lot, didn't knew that, now I can continue with my work...
Answer by MarkFinn · Dec 25, 2012 at 07:11 PM
There is no event occurring in most frames so the Event.current is almost always null (and so has no mouse position)
Perhaps adding the check
if(Event.current!=null && t.myRect.Contains(Event.current.mousePosition)){
will work?
I will try that, but when I make a class only in one file and do the same code above I don't have any errors with Event.current.mousePostion? I don't want to have a huge mess of classes functions loops in one file... need to organize that.. I will post if your answer solved the problem. thx for reply