GameObject not showing in script

85 views Asked by At

The public game object is missing in unity




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

public class SelectionManager : MonoBehaviour
{

    public GameObject Interaction_info_UI;
    Text interaction_text;
 
    private void Start()
    {
        interaction_text = Interaction_info_UI.GetComponent<Text>();
    }
 
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            var selectionTransform = hit.transform;
 
            if (selectionTransform.GetComponent<InteractableObject>())
            {
                interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
                Interaction_info_UI.SetActive(true);
            }
            else 
            { 
                Interaction_info_UI.SetActive(false);
            }
 
        }
    }
}





The script in unity

I've tried to download some extension to visual studio but hasn't done anything yet. The InteractableObject is a part if a different code that is working

1

There are 1 answers

3
Juris On

I guess your script didn't compile correctly, and there are errors in the console. This is why you're not seeing changes in the editor, such as your public value. From a glance, the error is your use of .GetComponent<> as a conditional bool type:

if (selectionTransform.GetComponent<InteractableObject>())

GetComponent will return null if it fails to get the component, so if you're looking to check if it exists on the transform, do a check for != null as such: if (selectionTransform.GetComponent<InteractableObject>() != null)

Better yet, look into TryGetComponent, which will simplify your conditional logic.