hamel123 hamel123 - 1 month ago 10
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

Material
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
canvas
gameobject
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
GameObject.Find("Canvas")
but error is coming. Also i try to solve this problem by using tags with this canvas by calling this function
GameObject.FindWithTag("Canvas")
but nothing works. Same error is coming.

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


Code:

public class Cube : MonoBehaviour {

[SerializeField] private bool check;


void OnMouseDown() {


if (!check) {

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


GameObject.Find("Canvas").SetActive(true);

check = true;

} else if (check) {

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

check = false;

}

}


}

Answer

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.

[SerializeField]
private bool check;

public GameObject myCanvas;

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