1

I have a problem in Unity 2d

NullReferenceException: Object reference not set to an instance of an object RightOne.OnMouseDown () (at Assets/Scripts/RightOne.cs:13) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

Here's the script:

using UnityEngine;
using System.Collections;

public class RightOne : MonoBehaviour {

    private GameObject mainCube;

    void Start () {
        mainCube = GameObject.Find ("Main Cube");
    }

    void OnMouseDown () {
        if (GetComponent <Renderer> ().material.color == mainCube.GetComponent <Renderer> ().material.color)
            mainCube.GetComponent <GameCntrl> ().next = true;
        else
            mainCube.GetComponent <GameCntrl> ().lose = true;
    }
}
derHugo
  • 68,790
  • 9
  • 58
  • 97
MaksNeon
  • 19
  • 3
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – BugFinder Apr 14 '20 at 13:45

1 Answers1

1

This means that something in your code in that function is null for example, GameObject.Find(..) returns null if the object cannot be found. GetComponent<T>() can also return null.

You need to make sure the gamecube is found, and the current gameobject and the main cube actually have a renderer component attached. The same is true for the GameCntrl component.

sommmen
  • 4,642
  • 1
  • 16
  • 33