- Home /
Deactivate UI windows in order when "Escape" button is pressed.
I can't come up with one script that will close UI windows in order that they are opened when "escape" is pressed. I can, of course, use a bunch of "if, else" in one script or create many scripts for every UI but these feel like inefficient solutions.
Answer by Eno-Khaon · Jan 07, 2021 at 05:22 AM
This is highly dependent on how you organize your UI, but here's a thought on what you could do.
First, create a simple Interface to assign to a script (if not just a script itself). It could even be empty, since it would conceptually just be a marker to say "this script can be closed with escape" and wouldn't need any logic itself.
When escape is pressed (as per your example), get the children of the main Canvas (or applicable Canvas), then start with the furthest down child (since, barring ordering/layering differences, that should be the one on top). Check whether it has the marker script and the GameObject is active. If so, deactivate the window.
// Simple implementation example
// Not the most efficient, nor the most thorough
// Also implicitly assumes that a newly opened window
// will be placed on top of other windows (Transform.SetAsLastSibling())
public class EscCloseMarker : MonoBehaviour
{
// Marker Class
}
public class EscToCloseWindow : MonoBehaviour
{
public Transform canvasT;
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
// Check children in ascending order
for(int i = canvasT.childCount - 1; i >= 0; i--)
{
Transform currentChild = canvasT.GetChild(i);
if(currentChild.gameObject.activeInHierarchy && currentChild.GetComponent<EscCloseMarker>() != null)
{
// Close selected window
currentChild.gameObject.SetActive(false);
}
}
}
}
}
Edit: Added check for activeInHierarchy
Thanks for the reply! But I don't understand what "EscClose$$anonymous$$arker" is for.
The "EscClose$$anonymous$$arker" class, by my example, would be there only to mark a window where "This UI element will be hidden when escape is pressed" -- The "EscToCloseWindow" class, in turn, would search for the last active child of the Canvas with the "EscClose$$anonymous$$arker" component attached to it. This way, only UI elements you would want to be affected, *CAN* be affected.
Your answer
![](https://koobas.hobune.stream/wayback/20220613022832im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Solutions for dynamic interface 0 Answers
Recreate Unity Editor Window in Game 0 Answers
Script Two Button Functions At Once 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers