Unity中提示‘缺失大括号’但代码无误的错误如何解决?
问题分析与解决方案
你的代码存在两处语法错误,控制台的“缺失大括号”属于编译器误报,实际问题如下:
局部变量不能添加访问修饰符
在Update()方法内部定义的horizontal、vertical、direction变量,不能使用private修饰符——C#语法规定局部变量不允许添加访问修饰符,直接去掉即可。变量名不匹配
你定义的移动速度变量是moveSpeed,但在调用charController.Move()时写的是未定义的speed,需要改为moveSpeed。
修正后的完整代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThirdPersonMovement : MonoBehaviour { [SerializeField] private CharacterController charController; [SerializeField] private float moveSpeed = 5f; void Update() { float horizontal = Input.GetAxisRaw("Horizontal"); float vertical = Input.GetAxisRaw("Vertical"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; if(direction.magnitude >= 0.1f) { charController.Move(direction * moveSpeed * Time.deltaTime); } } }
以上语法错误会导致编译器解析异常,进而抛出不准确的错误提示,修正后即可正常运行。
内容的提问来源于stack exchange,提问作者Cristopher
相关产品推荐
相关产品推荐

