-2

I am new to unity & trying to make small POC in MRTK. As a part of POC, I need to hide the Object when the button is clicked. Once Button is clicked it updates the current position of the Cube and should hide the Sphere. Position logic is working. But Error is displayed when trying to hide Sphere.

  • UnassignedReferenceException: The variable sph of ButtonBehaviour has not been assigned. You probably need to assign the sph variable of the ButtonBehaviour script in the inspector.

I created below C# script.

public GameObject sph;
   public void Example()
    {
        score++;
        aaz = Position();
        Textfeild2.text = score.ToString() + "New Pos =" + aaz;
        sph.SetActive(false);
    }

I attached the script to Game Object and dropped Sphere on sph and Updated the Onclick() of MRTK button. Am I missing anything else?

Attaching Image

Script attach- Sphere

  • The `Textfeild2` (typo btw) is not assigned ... your Inspector says `None` .. but you are trying to set its `Textfeild2.text = ...` – derHugo Oct 21 '22 at 07:54

1 Answers1

2

From what you provided, that should be working. Tips for debugging:

  • Type "t:ButtonBehaviour" in Project Explorer, to see if there are more than 1 scripts (one may have an unassigned variable)
  • Do you have anything in Start or Awake that may set the sph to null? A getComponent maybe? Also, sph is public, so other scripts could change that.
KYL3R
  • 3,877
  • 1
  • 12
  • 26
  • Hi, I have **START** and **UPDATE** but sph has no reference in them. I created a new function **HIDE** and added `sph.SetActive(false)` & it worked. As a newbie, can't we have more than one object reference in one function? – MAYANK PANDE Oct 21 '22 at 05:55
  • The reference count is not the problem. What does `OnButtonPress` do? That runs before `Example()` is called. Also, From the Screenshot, it looks like you call `Example` on the TextMeshPro first and then on the "GameObject". So you have at least 2 `ButtonBehaviour`s in your scene, I still guess one of them has null/empty ref in the inspector. – KYL3R Oct 21 '22 at 10:39