- Home /
Duplicate Question
Null RefferenceException Error when accessing bool from another script
Really don't need to explain much but basically one script needs to know when the game is over from another script. I have checked all over and I don't believe I am doing anything wrong but I am still getting an error (null reference exception.) Here is my code:
public bool GameOver;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
Movement movementScript = GetComponent<Movement>();
if(movementScript.GameOver == false)
{
GameOver = false;
}
if(movementScript.GameOver == true)
{
GameOver = true;
}
Debug.Log(GameOver);
if(EscClicked == false && GameOver == false)
{
Didn't copy the entire script on purpose ;) And here is the other script:
void OnTriggerEnter(Collider other)
{
GameOver = true;
Camera.mainCamera.transform.position = FinishedCameraPosition;
Camera.mainCamera.transform.rotation = FinishedCameraRotaition;
}
More than enough of this script ;)
Answer by aldonaletto · May 09, 2013 at 11:40 PM
For this to work, the script Movement must be attached to the same object as the script above. If it's attached to a different object, you must prefix GetComponent with a reference to this object - like this:
public GameObject movementObject; // reference to the object
void Update ()
{
// make GetComponent search in the object referenced by movementObject:
Movement movementScript = movementObject.GetComponent<Movement>();
// that's a much simpler way to copy the GameOver variable!
GameOver = movementScript.GameOver;
Debug.Log(GameOver);
if (EscClicked == false && GameOver == false)
...
Looks like his GameOver
var is in the main (1st) script, so the change would be in the 2nd, trigger, script, which needs to reach out.
Follow this Question
Related Questions
Object reference not set to instance of an object 2 Answers
script GetComponent, nullReference error 1 Answer
gameObject.GetComponent("Script").enabled = true not working 5 Answers
Object reference not set, simple script? 1 Answer
Unity event calling function gets nullreferencexception on bool 0 Answers