Search Unity

nullreferenceexpection...

Discussion in 'Scripting' started by LaiFany, Aug 23, 2014.

  1. LaiFany

    LaiFany

    Joined:
    Aug 23, 2014
    Posts:
    2
    Hey there. I bumped into a problem with my codes. Tried searching for an answer, but to no avail, since I've tried many solutions but failed. Here's my code. I'm trying to get the value of the godMode boolean, to be used in the birdFly script. But I keep getting the NullReferenceException error.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MenuText : MonoBehaviour {
    5.    
    6.     public bool quit = false;
    7.     public bool godMode = false;
    8.     void OnMouseEnter(){
    9.                 renderer.material.color = Color.red;
    10.         }
    11.     void OnMouseExit(){
    12.         renderer.material.color = Color.white;
    13.     }
    14.     void OnMouseDown(){
    15.                 if (quit)
    16.                         Application.Quit ();
    17.                 else
    18.             AutoFade.LoadLevel(1 ,1,1,Color.black);
    19.         }
    20. }
    21.  
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BirdFly : MonoBehaviour {
    5.     //public bool cheatMode = false;
    6.     Animator animator;
    7.     // Use this for initialization
    8.     void Start () {
    9.         animator = transform.GetComponentInChildren<Animator> ();
    10.         if (animator == null) {
    11.             Debug.LogError("No animator found!");
    12.                 }
    13.         }
    14.  
    15.     void OnCollisionEnter2D(Collision2D collision)
    16.     {
    17.         if ((GameObject.FindGameObjectWithTag("GodModeButton").GetComponent<MenuText>().godMode == true))
    18.             return;
    19.         animator.SetTrigger ("dead");
    20.         dead = true;
    21.     }
    22. }
    23.  
    Hopefully I can get some insights to solving this problem. Thanks in advance!
     
  2. daemon3000

    daemon3000

    Joined:
    Aug 13, 2012
    Posts:
    139
    There are two reasons why you could get a null reference exception. There is no gameobject with the GodModeButton tag in the scene or if it exists it doesn't have a MenuText component.
     
  3. LaiFany

    LaiFany

    Joined:
    Aug 23, 2014
    Posts:
    2
    There are both present. Both the GodModeButton object and also the Menu Text component. The BirdFly script is used by the player in another scene, but I don't think different scenes could cause this error. Or am I wrong?
     
  4. daemon3000

    daemon3000

    Joined:
    Aug 13, 2012
    Posts:
    139
    Both the BirdFly script and the MenuText script need to be in the same scene. When you try to get the GodModeButton component it returns null because it doesn't exist, it's in a different scene which is not loaded.