hamel123 hamel123 - 4 months ago 34
C# Question

Gameobject doesn't active on mouse click

I'm facing a problem in unity3d what i'm doing there is a gameobject which is a simple cube and
it's attach with a component called

which is in red color. Also there is a script attach to this
cube which is performing a event on left mouse click i.e it's change the color of material to green. The script
works fine but what i want in the scene there is a
which is default inactive. PictureI want to
active this gameobject when the material color is green or deactivate when the color is red. I'm using
a function called
but error is coming. Also i try to solve this problem by using tags with this canvas by calling this function
but nothing works. Same error is coming.

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


public class Cube : MonoBehaviour {

[SerializeField] private bool check;

void OnMouseDown() {

if (!check) {

gameObject.GetComponent<Renderer> ().material.color = Color.green;


check = true;

} else if (check) {

gameObject.GetComponent<Renderer> ().material.color = Color.red;

check = false;





GameObject.Find does not work when the GameObject is disabled. From the screenshot in your question, the Canvas GameObject is disabled.

That's why you are getting: NullReferenceException: Object reference not set to an instance of an object

Create a public variable for it and drag the Canvas there.

private bool check;

public GameObject myCanvas;

void OnMouseDown()
    if (!check)
        gameObject.GetComponent<Renderer>().material.color = Color.green;
        check = true;
    else if (check)
        gameObject.GetComponent<Renderer>().material.color = Color.red;
        check = false;