Forum rules - please read before posting.

Trying to access to a GameObject within a Unity UI (Prefab) via their RuntimeCanvas

edited May 2022 in Technical Q&A

[Unity 2019.4.38f1 - AC v1.75.2]

Hi!

I'm trying to activate\deactivate specific GameObjects that are children of a Menu (Unity UI Prefab). The UI is structured as such:

Canvas
\_ Panel
\_\_ ElementIWantToAccess

Given that what follows is probably bad practice, and that I could probably just attach a script to the ElementIWantToAccess that passes its reference upon initialization, to access it I'm trying to do something like this:

PlayerMenus.GetMenuWithName("Menu name").RuntimeCanvas.transform.Find("Panel/ElementIWantToAccess").gameObject

The problem being that the RuntimeCanvas is always null no matter when I try to access it.

I understand that using PrefabCanvas is not what I need to do (but please correct me if I'm wrong), so I went to look at how RuntimeCanvas is assigned in the Menu.cs script, specifically the LocateLocalCanvas() method, and I can see that, if menuSource is UnityUiPrefab, a localCanvas gets instantiated but no value is assigned to runtimeCanvas.

Is there something I'm missing?

Thanks in advance, as always!

Comments

  • Since RuntimeCanvas is what AC will affect when turning a Menu on and off, it should certainly be set if the UI prefab has been spawned in the scene.

    runtimeCanvas is assigned at the bottom of the LocateLocalCanvas method:

    if (menuSource == MenuSource.UnityUiInScene && localCanvas == null && runtimeCanvas)
    {
        // Special case: Loading a game in the same scene, but assigned canvas is disabled
    }
    else
    {
        runtimeCanvas = localCanvas;
    }
    

    The exception to this is when using Addressables for your UI prefab - is this the case?

  • Thanks for the answer!

    I think I have misread that very if, thinking it was an else if to the if (menuSource == MenuSource.UnityUiPrefab) at the top of the method. My apologies!

    So "cautious" of preparing all the elements before a menu actually displayed, it didn't occur to me that the RuntimeCanvas would only be initialized when the Menu turns on (and it makes absolute sense).

    Thanks again!

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.