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

Unity编写C#移动脚本补全大括号后语法错误仍存在如何解决

错误原因

你遇到的大括号缺失报错是编译器的误导性提示,实际问题和大括号数量无关:你在Update()方法内部错误使用了仅能作用于类成员字段的[SerializeField]序列化特性,C#编译器解析到方法内的非法特性声明时,会误判代码结构断裂,抛出缺失闭合大括号的错误,这种情况下盲目补大括号完全解决不了问题。

具体错误行是Update()方法内的:

[SerializeField] private float playerInputh = Input.GetAxisRaw("Horizontal");

playerInputh是方法内部的局部变量,本身不需要序列化,也不能加[SerializeField]标签。

修正后可运行代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Movement : MonoBehaviour {
 
    [SerializeField] private int speed = 10;
    [SerializeField] private int jump_height = 200;
    [SerializeField] private float m_smoothing = 0.14;

    private Vector3 m_Velocity = Vector3.zero;
    Rigidbody2D m_Rigidbody;

    public void Start() 
    {
        m_Rigidbody = GetComponent<Rigidbody2D>();
    }
    public void Update()
    {
        float playerInputh = Input.GetAxisRaw("Horizontal");
        Vector3 targetVelocity = new Vector2(playerInputh * speed, m_Rigidbody.velocity.y);
        m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_smoothing);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            m_Rigidbody.AddForce(new Vector2(0f, jump_height), ForceMode2D.Impulse);
        }
    }
       
}
补充说明
  • [SerializeField]的作用是让类里的私有字段显示在Unity编辑器的Inspector面板,方便调参,只能写在类的范围内、所有方法的外部,不能放在任何方法体内部
  • 按键检测优先用KeyCode.XXX枚举代替手写字符串,能避免拼写错误导致的输入失效
  • 2D跳跃给刚体加力时显式指定ForceMode2D.Impulse(瞬时冲量),比默认的持续力模式更符合跳跃的手感,不需要把跳跃力数值调得特别大

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 13:12:18