I’ve been tackling with this script for a while and I don’t have much understanding of C# so that probably doesn’t help…
Still, this is the script I have so far (Has undergone MANY changes since the original, which made more sense but still didn’t work, so please excuse any painfully obvious problems with the script.)
using UnityEngine;
using System.Collections;
public class MenuAppearScript : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown("escape"))
{
GameObject.MenuCanvas = SetActive(true) ;
}
}
}
Put this script on some other GameObject in the scene. I like to use an input manager or the canvas.
using UnityEngine;
using System.Collections;
public class MenuAppearScript : MonoBehaviour {
public GameObject menu; // Assign in inspector
private bool isShowing;
void Update() {
if (Input.GetKeyDown("escape")) {
isShowing = !isShowing;
menu.SetActive(isShowing);
}
}
}
Add a CanvasGroup to the Canvas if not there already and then set the Alpha to 0 (for invisible) or 1 (for visible), Also set the Interactive and BlocksRaycast false (when invisible) and true if visible.
Note the Alpha is a float so you can fade in or out of being visible if you want.
I know this is an old question, but it kept coming up in my search and I found a much better solution that I will share for reference.
This solution is in C# and the script needs to be attached to the canvas GameObject itself. It uses .enabled which is essentially ticking on and off the checkbox next to the name in the inspector panel.
MenuToggle.cs:
using UnityEngine;
using System.Collections;
public class MenuToggle : MonoBehaviour {
private Canvas CanvasObject; // Assign in inspector
void Start()
{
CanvasObject = GetComponent<Canvas> ();
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Escape))
{
CanvasObject.enabled = !CanvasObject.enabled;
}
}
}
With .SetActive I was having to press the key multiple times as the OP mentioned in the comments to the other solution.