I had this UI object referencing problem because I was attaching a MonoBehaviour to a “FullscreenToggle” Ui.Toggle that I’d added to a canvas, and in that script, I was trying to get a reference to the toggle like this:
Toggle targetToggle = gameObject as Toggle; // Nope!
But of course that doesn’t work because UI.Toggle is a Component, not a GameObject.
But when you create a Toggle and add it to the scene, the thing you add is definitely a GameObject. So that’s a bit confusing. Or it was to me, anyway - until I saw in the inspector that the GameObject I added to the scene had a Toggle Component.
When you add a UI Component (like a Toggle) to a canvas, it creates a GameObject subclass of a name you specify, and then adds a Toggle component to that GameObject, and adds (a meta data proxy for) an instance of that subclass into the scene as a child of the canvas.
If you add a MonoBehaviour to that GameObject, within there you can say
var toggle = GetComponent<Toggle>();
…(or whatever UI Component type you added) to get a reference to the Component itself.
And from some other script somewhere else, once you get a reference to the GameObject that has the Toggle as a component, you can say
var theComponent = theGameObject.GetComponent<TheComponentType>();
…to get access to it.
Ok, eliminating “extra” spaces and line breaks and filtering formatting tags like br is really annoying. This forum seriously needs some kind of formatting mark down other than just pre and code.
As for preserving UI elements across scenes - as long as both scenes reference the same game object instance (and the contained MonoBehaviour script and UI component) and not a separate copy (or copies), you should be able to call DontDestroyOnLoad, as demonstrated in this answer on Stack Overflow:
unity game engine - Share GameObjects between scenes - Stack Overflow