You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity交互物体失焦后UI Text未清空问题求助

Unity交互焦点丢失后UI文本未清空的偶发问题

背景代码

角色控制中的射线检测逻辑

我在Unity项目的角色控制脚本中,用射线检测判断玩家是否看向交互物体,所有可交互物体都被分配到Interactable层(层索引为6),核心检测代码如下:

private void HandleInteractionCheck()
{
    int layerMask = 1 << 6;

    if (Physics.Raycast(playerCamera.ViewportPointToRay(interactionRayPoint), out RaycastHit hit, interactionDistance, layerMask))
    {
        if (hit.collider.gameObject.layer == 6 && (currentInteractable == null || hit.collider.gameObject.GetInstanceID() != currentInteractable.GetInstanceID()))
        {
            hit.collider.TryGetComponent(out currentInteractable);

            if (currentInteractable != null)
            {
                currentInteractable.OnFocus();
            }
        }
    } else if (currentInteractable)
    {
        currentInteractable.OnLoseFocus();
        currentInteractable = null;
    }
}

可交互物体的UI控制脚本

给可交互物体添加了继承自Interactable的脚本,通过OnFocus()和OnLoseFocus()控制UI状态——比如门会根据开关状态显示"Open/Close + 物体名称",核心代码如下:

public class ActionText : Interactable
{
    [Header("Item Parameters")]
    [SerializeField] private TMP_Text interactionText;
    [SerializeField] private Image knob;

    private opencloseDoor openCloseScript; // 处理门开关逻辑的脚本

    private void Start()
    {
        openCloseScript = GetComponent<opencloseDoor>();
    }

    public override void OnFocus()
    {
        interactionText.text = openCloseScript.open ? "Close " + gameObject.name : "Open " + gameObject.name;
        knob.rectTransform.sizeDelta = new Vector2(50, 50);
    }

    public override void OnInteract()
    {
        print("INTERACTED WITH " + gameObject.name);
    }

    public override void OnLoseFocus()
    {
        interactionText.text = string.Empty;
        knob.rectTransform.sizeDelta = new Vector2(15, 15);
    }
}

问题

功能基本正常,但偶发交互物体失去焦点后UI文本未清空的情况,文本会停留在屏幕上——单独调用OnLoseFocus()方法时,文本能正常被清空。

补充信息

场景中的盒碰撞体截图:
盒碰撞体截图

内容的提问来源于stack exchange,提问作者skaptilian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:07:41