Search code examples
c#unity-game-enginevirtual-reality

Developing in Unity with XR Ray Interactable, selected objects can't be detected in different function within same script


This is my current script to hide a selected object with a press of a button (UI). The button has an onClick function assigned to Hide() and the SelectObject function is assigned to the object Select entered for XR Grab Interactable events:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HideObject : MonoBehaviour
{
    private GameObject selectedObject;

    public void Hide()
    {
        Debug.Log("Selected object in hide: " + selectedObject);
        if (selectedObject.activeInHierarchy)
        {
            selectedObject.SetActive(false);
        }
        else
        {
            selectedObject.SetActive(true);
        }
    }


    public void SelectObject(GameObject obj) 
    {
        selectedObject = obj;
        Debug.Log("Selected object " + selectedObject);
    }

}

However, the log tells me that selected object in SelectObject can be detected (the select works) but not that in Hide. I'm selecting an object using the controller grip button and hitting the button with the trigger of the controller.

An image is attached below to show hierarchy and logs:

errors

I've tried googling and looking at the forums for help but to no avail. Was wondering if it could be the trigger buttons (to select the UI button) resulting in overriding the original selected object.


Solution

  • I managed to solve it. I had 2 instances of the script running - one attached to the Hide button and the other to the GameObject. The one attached to the Hide button caused the null reference.

    To satisfy my requirements, I went ahead to create another script to reference the selected GameObject and then declare another function in the new script to hide the object on button click.