Unity移动系统脚本报错CS1526,请求排查问题及修复方案
Unity移动系统代码报错CS1526解决方法
你遇到的CS1526: A new expression requires (), [], or {} after type错误,是代码里的语法和逻辑问题导致的,具体问题和修正方案如下:
- 大小写问题:C#和Unity API对大小写敏感,
Input.getAxisRaw要改成Input.GetAxisRaw,vector2是系统内置类,必须写成Vector2(首字母大写)。 - new表达式语法错误:创建
Vector2实例时,必须用new Vector2(x值, y值)的格式,不能只写new vector2;。 - 位置赋值逻辑错误:
transform.position是值类型,直接修改x或y分量不会生效,需要重新赋值整个Vector2对象。
修正后的代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class moving_BEAN : MonoBehaviour { public float speed; void Update() { float h = Input.GetAxisRaw("Horizontal"); float v = Input.GetAxisRaw("Vertical"); // 计算新位置:当前位置加上方向*速度*帧时间(保证不同帧率下移动速度一致) Vector2 newPos = new Vector2(transform.position.x + h * speed * Time.deltaTime, transform.position.y + v * speed * Time.deltaTime); transform.position = newPos; } }
额外补充:加上Time.deltaTime可以让移动速度不受帧率影响,保证在不同设备上移动速度一致。
内容的提问来源于stack exchange,提问作者Orang4Fun
相关产品推荐
相关产品推荐

