Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Scripting' started by snmy, Jun 20, 2014.

  1. snmy

    snmy

    Joined:
    Jun 20, 2014
    Posts:
    3
    i am creating a game in which when i click two similar tiles, these tiles disappear. However, the error message "NullReferenceException: Object reference not set to an instance of an object" is appearing.

    I have this code for one tile:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Script11 : MonoBehaviour {
    5.  
    6.     public bool var;
    7.    
    8.     // Update is called once per frame
    9.     void onMouseDown () {
    10.    
    11.         var = true;
    12.     }
    13. }
    14.  

    while this is the other code

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Script00 : MonoBehaviour {
    5.    
    6.     void OnMouseDown()
    7.     {
    8.                 Script11 otherScript = GetComponent<Script11> ();
    9.                 if (otherScript.var = true) {
    10.  
    11.                         Destroy (this.gameObject);
    12.                 }
    13.         }
    14.  
    15. }


    PLEASE HELP! thanks in advance =)
     
  2. Erisat

    Erisat

    Joined:
    Jan 31, 2013
    Posts:
    88
    dont call your bool var. name it something else.
     
  3. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Also, Google is your friend. This question has been posted and answered many times before.
     
  4. Erisat

    Erisat

    Joined:
    Jan 31, 2013
    Posts:
    88
    are those two scripts on separate objects? i assume so. your using getcomponent<script11> in the script00. if theyre on separate objects, this wont work as getcomponent will get components will only get a component within the same object as the script that called it. (when used that way). you could store a reference to the script11's gameobject in script00, and then use something like: script11gameobject.GetComponentblahblah

    so you may be getting a null reference because your trying to access a component that doesnt exist in that context.

    what line does the error show up on specifically?
     
  5. Erisat

    Erisat

    Joined:
    Jan 31, 2013
    Posts:
    88
  6. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    389
  7. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    needs to be a capital O as well
     
    Erisat likes this.
  8. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942