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

Unity触发器+按键切换场景问题:IF语句失效排查求助

问题原因分析

你的核心问题出在Input.GetButtonDown的检测时机和OnTriggerEnter2D的执行逻辑不匹配:

  • OnTriggerEnter2D仅在玩家进入触发器的单一帧内执行一次
  • Input.GetButtonDown("Action")仅在按键被按下的那一帧返回true
  • 这两个事件恰好同时发生的概率几乎为0,所以你的IF语句永远不会触发场景切换

对比你目标场景的脚本,它是在Update函数里做检测——Update每一帧都会执行,所以能持续捕获按键输入,自然能正常触发场景切换。

修复方案

需要添加一个布尔变量标记玩家是否处于触发器范围内,然后在Update里持续检测按键输入:

修改后的完整脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class entryDining : MonoBehaviour
{
    public GameObject ThePlayer;
    public GameObject uiPanel;
    public GameObject textBox;
    public string actionText;
    public string scene;

    // 标记玩家是否在触发器内
    private bool isPlayerInTrigger = false;

    void OnTriggerEnter2D(Collider2D other)
    {
        // 确保是玩家触发的触发器
        if(other.gameObject == ThePlayer)
        {
            textBox.GetComponent<Text>().text = actionText;
            uiPanel.SetActive(true);
            textBox.SetActive(true);
            isPlayerInTrigger = true;
        }
    }

    void OnTriggerExit2D(Collider2D other)
    {
        if(other.gameObject == ThePlayer)
        {
            uiPanel.SetActive(false);
            textBox.SetActive(false);
            isPlayerInTrigger = false;
        }
    }

    void Update()
    {
        // 玩家在触发器内且按下Action键时切换场景
        if(isPlayerInTrigger && Input.GetButtonDown("Action"))
        {
            SceneManager.LoadScene(scene);
        }
    }
}
额外优化点
  • 在触发器事件里添加玩家对象判断,避免其他碰撞体误触发UI
  • 退出触发器时同步隐藏文本框,保持界面逻辑一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:32:31