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

Unity游戏暂停时如何冻结相机?

FPS暂停菜单问题:暂停时鼠标仍控制相机

我正在制作第一款FPS游戏,碰到了暂停菜单的bug——游戏暂停后,鼠标还能控制相机,点击菜单按钮时相机也会跟着鼠标移动。网上搜了一圈没找到合适的解决方案,我的代码和搜到的示例逻辑差不多,贴出来求助:

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

public class PauseMenu : MonoBehaviour
{
    public static bool gameIsPaused;
    public GameObject pauseMenuUI;
    
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        { 
            Pause();
        }
    }

    public void Resume()
    {
        Cursor.lockState = CursorLockMode.Locked;
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        gameIsPaused = false;
    }
    
    void Pause()
    {
        Cursor.lockState = CursorLockMode.None;
        pauseMenuUI.SetActive(true);
        gameIsPaused=true;
        Time.timeScale = 0f;
    }

    public void LoadMenu()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene("Menu");
    }

    public void QuitGame()
    {
        Debug.Log("Quitting game...");
        Application.Quit();
    }
}

问题根源

你的暂停代码只处理了UI显示、时间缩放和光标状态,但相机控制脚本没收到暂停信号,还在继续读取鼠标输入。Time.timeScale = 0只会影响依赖Time.deltaTime的逻辑,但多数FPS相机控制会直接读取Input.GetAxis("Mouse X/Y"),这个输入不受时间缩放影响。

解决步骤

  1. 给相机控制脚本添加暂停判断
    找到你的相机控制脚本(比如PlayerCamera),在处理鼠标移动的逻辑前加判断:
void Update()
{
    // 仅游戏未暂停时处理相机旋转
    if (!PauseMenu.gameIsPaused)
    {
        float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
        // 你的相机旋转逻辑代码...
    }
}
  1. 完善光标状态控制
    暂停时确保光标可见,恢复时隐藏:
void Pause()
{
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true; // 新增:显示光标
    pauseMenuUI.SetActive(true);
    gameIsPaused = true;
    Time.timeScale = 0f;
}

public void Resume()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false; // 新增:隐藏光标
    pauseMenuUI.SetActive(false);
    Time.timeScale = 1f;
    gameIsPaused = false;
}
  1. 修复重复触发暂停的问题
    修改Update逻辑,让Esc键实现暂停/恢复的切换:
void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        if (gameIsPaused)
        {
            Resume();
        }
        else
        {
            Pause();
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:25:17