- Home /
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!
Answer by KdRWaylander · Apr 02, 2015 at 08:06 AM
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: https://www.youtube.com/watch?v=Mzt1rEEdeOI
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.
$$anonymous$$dRWaylander, I am using your script to make a canvas popup on pressing a keycode but after putting it in I had to change some parts of the code to get it to work and even after doing that it still won't popup the canvas, what am I missing?alt text
Your answer
Follow this Question
Related Questions
Canvas buttons and fullscreen aspect ratio 1 Answer
Screen Space - Camera Bug (Buttons does not work) on Unity 2017 0 Answers
Menu not getting Keyboard Input 0 Answers
Lock the screen 1 Answer
UNFIT SCREEN SIZE FOR MOBILE 0 Answers