Unity CS0117报错:'Input'不含'getAxis'定义求助
问题原因
C# 为大小写敏感语言,Unity 内置 Input 类的所有公开API统一采用帕斯卡命名规则(所有单词首字母大写),你的代码中存在3处API名称大小写错误,直接触发CS0117编译器报错:
- 代码第49行、51行写的
Input.getAxis()为错误写法,正确方法名为Input.GetAxis()(Get首字母需大写) - 代码第38行写的
Input.getKeyDown()为错误写法,正确方法名为Input.GetKeyDown()(Get/Key/Down三个单词首字母均需大写)
额外逻辑问题:代码中重复写了两套移动逻辑,第一套是带相机朝向平滑转向的移动实现,第二套是基于世界坐标轴的生硬移动实现,两套逻辑同时调用 controller.Move 会导致转向失效、移动手感错乱。
修复方案
- 修正所有Input类方法的大小写错误
- 删除重复的冗余移动逻辑,合并重力、跳跃、平面移动的速度计算,避免多次调用移动接口产生冲突
修正后可直接运行的完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThirdPersonMovement : MonoBehaviour { public CharacterController controller; public float speed = 6f; public float turnSmoothTime = 0.1f; public Transform cam; private float verticalVelocity; private float gravity = 14.0f; private float jumpForce = 10.0f; float turnSmoothVelocity; void Update() { float horizontal = Input.GetAxisRaw("Horizontal"); float vertical = Input.GetAxisRaw("Vertical"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; // 处理重力与跳跃 if (controller.isGrounded) { verticalVelocity = -gravity * Time.deltaTime; if (Input.GetKeyDown(KeyCode.Space)) { verticalVelocity = jumpForce; } } else { verticalVelocity -= gravity * Time.deltaTime; } // 处理平面移动与转向 if (direction.magnitude >= 0.1f) { float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; Vector3 finalMove = moveDir.normalized * speed * Time.deltaTime; finalMove.y = verticalVelocity * Time.deltaTime; controller.Move(finalMove); } else { // 无移动输入时仅应用垂直方向重力/跳跃速度 controller.Move(new Vector3(0, verticalVelocity * Time.deltaTime, 0)); } } }
提示:Unity所有C#内置API的方法、属性、类名均遵循帕斯卡命名规则,书写时注意首字母大写,不要和局部变量、私有字段的驼峰/下划线命名规则混淆。
内容的提问来源于stack exchange,提问作者Capmn'
相关产品推荐
相关产品推荐

