using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; using UnityEngine.UI; public class UINavigator : MonoBehaviour { [SerializeField] string firstSelectButtonTagName = "EntryButton"; float pulseRate = 8f; float amplitude = .2f; Image image = null; Color color; Selectable lastSelected; void OnEnable() { SceneManager.sceneLoaded += SelectFirstButton; } void OnDisable() { SceneManager.sceneLoaded -= SelectFirstButton; } void SelectFirstButton(Scene s, LoadSceneMode m) { StartCoroutine(SelectFirstButtonCoroutine()); } IEnumerator SelectFirstButtonCoroutine() { if (!string.IsNullOrEmpty(firstSelectButtonTagName)) { float startTime = Time.time; while (Time.time < startTime + 1f) { yield return new WaitForEndOfFrame(); GameObject go = GameObject.FindGameObjectWithTag(firstSelectButtonTagName); if (go == null) { continue; } if (go.GetComponent() == null) { continue; } EventSystem.current.SetSelectedGameObject(go); break; } } } void Update() { EventSystem eventSys = EventSystem.current; // 鼠标点击取消 if (Input.GetMouseButtonDown(0)) { UnSelect(); } if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } if(eventSys.currentSelectedGameObject == null) { return; } Selectable selected = eventSys.currentSelectedGameObject?.GetComponent(); if (selected != null && image != null) { float pulse = .5f + .5f * Mathf.Sin(Time.unscaledTime * pulseRate); float value = 1 - amplitude * pulse; Color col = color * value; col.a = 1f; image.color = col; //Debug.Log(selected.gameObject); } if (selected != lastSelected) { UnSelect(); if (selected) { image = selected.GetComponent(); if (image != null) { color = image.color; } } lastSelected = selected; } KeyCode keyCode = KeyCode.None; if (Input.GetKeyDown(KeyCode.LeftArrow)) { keyCode = KeyCode.LeftArrow; } else if (Input.GetKeyDown(KeyCode.RightArrow)) { keyCode = KeyCode.RightArrow; } else if (Input.GetKeyDown(KeyCode.UpArrow)) { keyCode = KeyCode.UpArrow; } else if (Input.GetKeyDown(KeyCode.DownArrow)) { keyCode = KeyCode.DownArrow; } if (keyCode != KeyCode.None) { // 没有已选择的UI,寻找第一个 if (selected == null || !selected.isActiveAndEnabled) { Selectable firstSelectable = FindObjectOfType(); if (firstSelectable != null) { eventSys.SetSelectedGameObject(firstSelectable.gameObject); } } // 通过已选择的UI,寻找下一个 else { switch (keyCode) { case KeyCode.LeftArrow: selected = selected.FindSelectableOnLeft(); break; case KeyCode.RightArrow: selected = selected.FindSelectableOnRight(); break; case KeyCode.UpArrow: selected = selected.FindSelectableOnUp(); break; case KeyCode.DownArrow: selected = selected.FindSelectableOnDown(); break; } } } } void UnSelect() { if (image != null) { image.color = color; image = null; } } }