- Home /
Access a counter in another script in scene(NullReferenceException: Object reference not set to an instance of an object)
Hello,
I am trying to make a block falling game in unity. In my scene I have two scripts, the first is called 'GameBehaior' and is attached to my GameController. The second is called 'PillBehavior' and is attached to the capsule gameobject at runtime. The GameBehavior script has a integer in it called counter. My PillBehavior script is trying to access the counter in the GameBehavior script. However when I try to use Debug.Log to print out the counter to check if it is working I get the following error "NullReferenceException: Object reference not set to an instance of an object"
The code that I am using to try to get the counter out of GameController in PillBehavior is this:
gamecontroller = GameObject.FindGameObjectWithTag ("GameController");
script = gamecontroller.GetComponent<GameBehavior> ();
Debug.Log (script.counter);
The debug line is the line that is giving me the NullReferenceError
Script and gamecontroller are defined like this:
GameObject gamecontroller;
public GameBehavior script;
Also, I dont know if this matters are not but counter is defined like this in the GameBehavior script:
public int counter; //number of pills on the screen
Answer by Tourist · Oct 07, 2014 at 03:50 PM
As the error said, you have a null variable.
if the error points to the second line : gamecontroller is null. This means that there is no object with that tag in the scene (or maybe the object is inactive).
if the error points to the third line : script is null. This means there is no component of type 'GameBehavior' in the game object returned the line above. It could happen if you have more than one object tagged with GameController and you got the wrong one. If you have the correct game object returned, then the component is not part of the game object.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Can't explain an NRE 0 Answers
2D toolkit object instance error 0 Answers
Scripting help,.where to start? 0 Answers
Trouble with Null Reference in Script 2 Answers