A UI component that toggles a 'menu' component on a GameObject named "UI" when the Escape key is pressed. It finds the UI GameObject on start, listens for Escape in updates on the authoritative instance, and adds or destroys the menu component; it also ensures the menu is destroyed when this component is destroyed.
using Sandbox;
using Sandbox.ui;
public class Menu : Component {
GameObject UI;
protected override void OnStart() {
UI = Scene.Directory.FindbyName("UI");
}
protected override void OnUpdate() {
if (IsProxy) return;
if (Input.EscapePressed) {
Input.EscapePressed = false;
if (UI.Components.TryGet<menu>(out var _)) {
UI.GetComponent<menu>().Destroy(); return;
}
UI.AddComponent<menu>();
}
}
protected override void OnDestroy() {
if (!IsProxy && UI.Components.TryGet<menu>(out var _))
UI.GetComponent<menu>().Destroy();
}
}