Unity开发时无法为GameObject添加脚本 无终端报错求助
你代码里存在多处语法错误,是导致无法挂载脚本的核心原因,具体问题如下:
- 字段声明漏写分号:
public float mouseY、Vector2 cameraInput两行末尾均缺少分号,C#要求每条语句以分号结尾。 - 方法修饰符重复冗余:
OnEnable方法错误写为public void private void OnEnable(),OnDisable方法错误写为private void private void OnDisable(),一个方法只能有一个返回值声明和一个访问修饰符,OnEnable/OnDisable作为Unity生命周期方法,直接用private void修饰即可。 - 大括号层级错误:
OnEnable方法内部多了一层多余的大括号,且方法末尾缺少闭合大括号,同时类内的大括号位置错误,导致TickInput、MoveInput两个方法被写在了InputHandler类的外部,不属于MonoBehaviour子类的成员,无法被Unity识别。 - 变量名拼写不统一:类中声明的字段为
moveAmountl,但在MoveInput方法中错误写为moveAmountv,两者不一致导致变量未定义报错。 - 方法名大小写错误:
Mathf.abs应写为Mathf.Abs,C#对大小写敏感,Unity的Mathf工具类方法首字母均为大写。 - Lambda参数名冲突:Movement事件绑定的Lambda参数名
inputActions和类成员变量inputActions重名,会导致上下文引用冲突。
修正后的完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace LE { public class InputHandler : MonoBehaviour { public float horizontal; public float vertical; public float moveAmount; public float mouseX; public float mouseY; PlayerControls inputActions; Vector2 movementInput; Vector2 cameraInput; private void OnEnable() { if (inputActions == null) { inputActions = new PlayerControls(); inputActions.PlayerMovement.Movement.performed += ctx => movementInput = ctx.ReadValue<Vector2>(); inputActions.PlayerMovement.Camera.performed += i => cameraInput = i.ReadValue<Vector2>(); } inputActions.Enable(); } private void OnDisable() { inputActions.Disable(); } public void TickInput(float delta) { MoveInput(delta); } private void MoveInput(float delta) { horizontal = movementInput.x; vertical = movementInput.y; moveAmount = Mathf.Clamp01(Mathf.Abs(horizontal) + Mathf.Abs(vertical)); mouseX = cameraInput.x; mouseY = cameraInput.y; } } }
修正后请确保脚本文件名和类名InputHandler完全一致,即可正常挂载到GameObject上。
内容的提问来源于stack exchange,提问作者Gufflim
相关产品推荐
相关产品推荐

