Hello,
I created a “CanvasMenu” canvas. It should be the parent for all my sub-menus.
I added two childs to that canvas.
One: “MenuPanel” with Buttons as childs like Continue, Start new, Quit …
Two: “MenuStartPanel” with Buttons as cilds for Options for a new game…
Both are active in the inspector.
When starting first I initialize the view:
public static void Init()
{
GameObject.Find(“MenuPanel”).SetActive(true);
GameObject.Find(“MenuStartPanel”).SetActive(false);
}
Looks okay and I see the first “MenuPanel” the other not. Perfect.
But when clicking new game I want to Change visibility:
GameObject.Find (“MenuPanel”).SetActive (false);
GameObject.Find (“MenuStartPanel”).SetActive (true);
This does not work, it gets a Null exception. Why does it not work?
If I use SetActive(false) is it gone forever then?
What is the best way to control my menu?
I do not want to have a unity Scene for each one, I get other Problems then…
Thanks a lot,
Firlefanz
Look at the GameObject.Find documentation:
It clearly state it only returns active gameobjects, so once you deactivated it it’s unable to find it again.
You can fix this by keeping a reference to them, for example create a start method (you also need to get rid of the static qualifier in your Init method):
private GameObject menuPanel;
private GameObject menuStartPanel;
void start () {
menuPanel = GameObject.Find ("MenuPanel");
menuStartPanel = GameObject.Find ("MenuStartPanel");
}
public void Init()
{
menuPanel.SetActive (true);
menuPanel.SetActive (false);
}
2 Likes
Thanks a lot. This helps!
Forgot to reply to this. I’m not sure I use the best workflow, but here’s how I handle it in my current project:
I have a main menu scene, containing only the main menu (this ensure the initial scene loads quickly, especially on lower end computers).
From there the user can start a new game, if he does there’s a loading screen with a slider and the 1st game scene is loaded asynchronously.
The game scenes are containing the ingame menu that shows when you press ESC to pause the game. The user can choose to return to the main menu in which case the loading screen is showed and main menu loaded asynchronously.
I used prefabs to handle my menu across the different scenes.
EDIT: just noticed I made a typo in the code I posted above. The start method should have a capitalized S (Start).
You can check at MonoBehaviour documentation to get the list of useful methods:
http://docs.unity3d.com/ScriptReference/MonoBehaviour.html
Thanks for your hints!
Do you have any experience with the oculus by the way?
Nope, I’m sorry but I’ve never played with this great tool…