- Home /
NullReferenceException: Object reference not set to an instance of an object
I searched for "NullReferenceException: Object reference not set to an instance of an object" but I don't get it for the code I have below.
Please help take a look at the following code. I'm trying to understand why its giving me this error.
The question is what do I need to do to make object ac not null? What is the correct way to doing this?
NullReferenceException: Object reference not set to an instance of an object
public class PlayerTrigger : MonoBehaviour {
public GUIText points_text;
public Access ac;
void Awake()
{
ac = GetComponent<Access>();
ac.total = 0;
if (ac == null)
{
Debug.Log ("ac is null.");
}
}
public class Access : MonoBehaviour
{
public int total_score(int point)
{
return total += point;
}
public int total
{
get {return m_total;}
set {m_total = value;}
}
private int m_total;
}
This code is attempting to the the 'Access' component on the same game object as this script is attached to. The two most likely reasons you are getting a null are:
The 'Access' component is not on the same game object as this script...maybe it is on a child object or some other game object.
You have two (or more) game objects that have the 'PlayerTrigger' script attached, but not all of those game objects have an 'Access' script attached.
simple m_total must be null, which makes total_score null. so set a default value for m_total;
I'll further test @robertbu's comments. Changed code from @Fornoreason1000's comments but still the same.
Answer by shophongkong · Mar 21, 2014 at 08:47 AM
I've updated to the following. It works now. I removed the part monobehavior and used new Access to create object.
public class Access
{
public int total_score(int point)
{
return total += point;
}
public int total
{
get {return m_total;}
set {m_total = value;}
}
private int m_total;
}
code speaks 1000 words. run this code, and check for results in your console
public class Access : $$anonymous$$onoBehaviour
{
public int total_score(int point)
{
Debug.Log("$$anonymous$$TOTAL is" + m_total.ToString());
Debug.Log("total is" + total.ToString())
return total += point;
}
public int total
{
get {return m_total;}
set {m_total = value;}
}
private int m_total;
}
also ac.total should be after the if commands, not before, Why? well your want to check for null be your trying to reference something before that, so what will happen is the compiler will stop running code once it hits the null ac when you access total from it. this means AC could be null but your if block will never actually be run in code. so when you check for null, do it before you do anything else after GetComponent() otherwise you are wasting your time.
hope it helps.
Your answer
Follow this Question
Related Questions
Device Simulator - Null Reference Error 0 Answers
Base class variables not initialized for sub class? 1 Answer
NullReferenceException - Why? 2 Answers