Search Unity

NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by chikoo, Mar 24, 2013.

  1. chikoo

    chikoo

    Joined:
    Jan 5, 2013
    Posts:
    12
    Hi, I am trying to access a variable in an outside script but keep getting the

    "NullReferenceException: Object reference not set to an instance of an object"

    error message

    I don't really understand why I am getting it or how to fix it. Any help and explanation would be greatly appreciated.

    The error is occurring because of this code

    "GameObject.Find("ScriptObject").GetComponent<QuestionsHolder>().isAskingQuestion = false;"

    Thanks in advance!

    ========================================

    public class IsAnswerCorrect : MonoBehaviour {

    private Ray ray;
    private RaycastHit rayCastHit;
    public string correctKeyPress;

    // Use this for initialization
    void Start ()

    {

    }

    // Update is called once per frame
    void Update ()
    {

    if(Input.GetMouseButtonDown(0))
    {
    ray = Camera.main.ScreenPointToRay (Input.mousePosition);

    if (Physics.Raycast (ray, out rayCastHit))
    {
    if(rayCastHit.transform.tag == correctKeyPress)
    {
    Debug.Log("correct");
    GameObject.Find("ScriptObject").GetComponent<QuestionsHolder>().isAskingQuestion = false;
    }
    else
    {
    Debug.Log("wrong");
    }

    }

    }

    }

    }
     
  2. EliteMossy

    EliteMossy

    Joined:
    Dec 2, 2012
    Posts:
    513
    remove the space from Quest ionsHolder should be QuestionsHolder.
    Also use code blocks for code.

    If that fails try to break the code down:
    Code (csharp):
    1.  
    2. GameObject.Find("ScriptObject").GetComponent<QuestionsHolder>().isAskingQuestion = false;
    3.  
    could be done like this to check for what is failing
    Code (csharp):
    1.  
    2. GameObject go = GameObject.Find("ScriptObject");
    3.    if (go != null){
    4.     QuestionsHolder questionsHolder = go.GetComponent<QuestionsHolder>();
    5.                   if (questionsHolder != null){
    6.                        questionsHolder.isAskingQuestion = false;
    7.                    }else{
    8.                         Debug.Log("Could not find component QuestionsHolder");
    9.                    }
    10.     }else{
    11.          Debug.Log("Culd not find GameObject ScriptObject");
    12.     }
    13.