I try to make a game menue that only shows up when the player clicks on a game object. I have a main canvas which contains a child canvas. the child canvas contains my game menue. Now I would like to display this child canvas when the user clicks on a game object. The game object contains a script for the click. I tried following so far, but it doesn’t work:
Does it work as you want it to when disabling ‘MyCanvas’ in the inspector?
Is a NullReferenceException thrown? Or does it simply not react when clicking?
It’s still far, far better to create a public Canvas and drag and drop the canvas into the script in the editor if you are creating it ahead of time. Things are different if you are creating them with a script but if you aren’t the reference is the best option. Other than that yes, enabled = true is the way to turn it on.
In the Monobehavior class that is enabling and disabling…
using UnityEngine.UI;
[SerializeField]
private Canvas myCanvas; // or whatever you want to call it
//then in your functions you simply call
myCanvas.enabled = true;
Then in the inspector, on the object that has this code on it as a component, there should be a slot for MyCanvas. You can drag the Gameobject that has your Canvas on it into this slot, and you are all hooked up.
How can I assign the Canvas reference to that variable when my gameobject is created dynamiclly through another script? When I use GameObject.Find(“/Canvas/MyCanvas/”) then I get a compiler error that it can’t convert GameObject to UI
Because you’re probably trying to assign a gameObject to the variable ‘myCanvas’ in the sample code above, which is of type Canvas. You can try to use GetComponent() of the object that you found with the line you posted.