using UnityEngine; using TMPro; using UnityEngine.EventSystems; using System.Collections; public class CustomTMPInputField : TMP_InputField { private bool forceFocus = false; protected override void Awake() { base.Awake(); } public override void OnPointerClick(PointerEventData eventData) { base.OnPointerClick(eventData); if (!forceFocus) { Activate(); } } public override void OnDeselect(BaseEventData eventData) { if (forceFocus) { StartCoroutine(DelayedSelect()); } else { base.OnDeselect(eventData); } } private IEnumerator DelayedSelect() { yield return null; if (EventSystem.current != null && EventSystem.current.currentSelectedGameObject != gameObject) { EventSystem.current.SetSelectedGameObject(gameObject); // TMP 原生激活输入框,显示光标 ActivateInputField(); // 强制同步 placeholder 状态 ForceRefresh(); } } /// /// 激活并保持焦点 /// public void Activate() { forceFocus = true; StartCoroutine(DelayedSelect()); } /// /// 主动关闭焦点 /// public void Deactivate() { forceFocus = false; DeactivateInputField(); if (EventSystem.current != null && EventSystem.current.currentSelectedGameObject == gameObject) EventSystem.current.SetSelectedGameObject(null); ForceRefresh(); } /// /// 是否有焦点 /// public bool HasFocus() { return forceFocus && isFocused; } /// /// 手动切换到另一个输入框 /// public void SwitchFocus(CustomTMPInputField nextField) { if (nextField == null) return; ForceRefresh(); Deactivate(); nextField.Activate(); nextField.ForceRefresh(); } /// /// 强制刷新 placeholder 状态 /// public void ForceRefresh() { if (placeholder != null) placeholder.gameObject.SetActive(string.IsNullOrEmpty(text) && !isFocused); } }