-2

I have a C# code where I am receiving NullReferenceException at line 15. I have some menus on my application (named "meniu1" or "meniu3"). Initially they are both activated, but depending on a variable I am trying to activate only one of them. Does anybody know why am I receiving null exception, I am new in unity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class script1 : MonoBehaviour
{
void Start()
{
    if (staticscrpt.checkvalue == true)
    {
        GameObject.Find("meniu1").SetActive(false);
    }
    else if (staticscrpt.checkvalue == false)
    {
        GameObject.Find("meniu3").SetActive(false);
    }
   
    staticscrpt.checkvalue = false;

}

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

}
public void trig_function (){
    if (staticscrpt.checkvalue == false)
    {
        SceneManager.LoadScene("AR");
        staticscrpt.checkvalue = true;
    }
}

}

Tatta13
  • 3
  • 3
  • Please remember to mark or highlight which line the error is on (eg, with a comment in the code). We can't see the line numbers. – Immersive Feb 18 '21 at 15:18

2 Answers2

0

GameObject.Find("meniu3") is probably returning null instead of the expected GameObject (check the name of the gameobject: it is "meniu3" or "menu3"? ).

You get a NullReferenceException because you are trying to call SetActive on the result of GameObject.Find and you can't call it if this method has returned null.

Pierre Baret
  • 1,773
  • 2
  • 17
  • 35
0

Most sources give the explanation that a GameObject.Find can only return Null if the GameObject to be called is inactive. To be able to find the gameobject it needs to be active. I would suggest placing the GameObject(s) in it's own global variable, which is set to active, and then using the setActive method to set it to inactive.

Sources:

Iliass Nassibane
  • 651
  • 7
  • 15