How do i pop up a canvas, when a click some key from keyboard?

Hi people, so my doubt is this.
How do i pop up a canvas, when a click some key from keyboard?

for example, i’m controlling a 3rd person controller through a house, and when i’m trying to open a door, i want to open some canvas or UI or show me some buttons, that give me some actions to do with this same door:

  • knock knock!
  • ring the bell
  • pull the key
  • just open the door

first off all, i’m sorry about my poor english, but i hope you understood my doubt.

best regards!

unity FTW!

Hi,

You want to use the ‘SetActive’ function of your canvas (and to be listening to your keyboard) !

Let’s say you wanna use ‘E’ to interact with the door, you will want to write a script in which as soon as you use the E key, the canvas will be active (and thus visible) and when you press E again, the canvas will be hidden.

C#:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// put this script on any gameobject, i personally use an empty 'root' gameobject on which i put all my scripts alike
public class ToggleDoorCanvas : MonoBehaviour {
	public Canvas doorCanvas;	// now you have to drag and drop your canvas in the editor in the script component
	private bool doorActive = false; // do we have to display the canvas (true) or not (false)
	
	void Update () {
		if(Input.GetKeyDown(Keycode.E)){ // if you press the E key
			doorActive = !doorActive; // change the state of your bool
			doorCanvas.transform.SetActive(doorActive); // display or not the canvas (following the state of the bool)
		}
	}
}

Now that’s not perfect because it will display the canvas wherever you are, far from the door or not, whatever you’re doing, pressing E will display the canvas. What you can do to improve the solution:

  • Use a ‘world canvas’ instead of a classic canvas that is stuck on you camera, that will display the canvas ‘in the world’ like a gameobject: Unity 4.6 - New UI World Space Canvas - YouTube
  • Use raycast to fire a limited-range ray in front of you to detect if there’s a door or not and if it’s the case display the canvas.