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

Unity中Input.GetAxisRaw方法调用报错求助

解决Unity中GetAxisRaw调用错误的问题

错误提示的核心是某个Input相关API被在MonoBehaviour的构造函数或实例字段初始化阶段调用了,而非你贴出的Update方法里的GetAxisRaw调用有问题——Update属于Unity帧更新周期的合法调用时机,你之前的使用经验是正确的。

你需要重点检查mouseDown变量的定义:

  • 如果mouseDown是类的成员字段,且你直接用Input方法初始化它(比如写成bool mouseDown = Input.GetMouseButton(0);),这就是错误触发点——字段初始化操作在类构造阶段执行,此时Unity的Input系统尚未完成初始化,不允许调用这类API。

修正方案:
把mouseDown的状态检测移到Update方法内执行,示例代码如下:

void Update()
{
    // 实时在Update内更新鼠标按下状态,而非字段初始化时赋值
    bool mouseDown = Input.GetMouseButton(0);
    if (mouseDown)
    {
        float xInput = Input.GetAxisRaw("Horizontal");
        float yInput = Input.GetAxisRaw("Vertical");
        cam.Translate(xInput * movingSpeed, yInput * movingSpeed, 0);
    }
}

若mouseDown需要作为类成员变量复用,也仅在Update内赋值:

private bool mouseDown;

void Update()
{
    mouseDown = Input.GetMouseButton(0);
    if (mouseDown)
    {
        float xInput = Input.GetAxisRaw("Horizontal");
        float yInput = Input.GetAxisRaw("Vertical");
        cam.Translate(xInput * movingSpeed, yInput * movingSpeed, 0);
    }
}

额外提醒:如果你的脚本中还有其他用Input相关API直接初始化的字段(比如其他变量用Input.GetAxis赋值),也需要将这些赋值操作移到Awake、Start或Update方法中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:11:02