Unity GetComponent导致错误

本文关键字:错误 GetComponent Unity | 更新日期: 2023-09-27 18:03:20

我有一个非常基本的动画动作脚本,但我甚至无法进入实际的动画部分因为我得到了这个错误:

Assets/Player Controllers/PlayerController.cs(18,41): error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected

直到今天它给了我一个关于GetComponent的错误,但现在我甚至不能复制,尽管我没有改变一行代码。总之,完整的内容是:

using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour{
public float runSpeed = 6.0F;
public float jumpHeight = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Start(){
    controller = GetComponent<CharacterController>();
    animController = GetComponent<Animator>();
}
void Update(){
    if(controller.isGrounded){
        moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;
        if(moveDirection = Vector3.zero){//Stopped
            isWalking = false;
            isBackpedaling = false;
        }else if(moveDirection = Vector3.back){//Backpedaling
            animController.isWalking = false;
            animController.isBackpedaling = true;
        }else{//Walking
            animController.isWalking = true;
            animController.isBackpedaling = false;
        }
        if(Input.GetButton("Jump")){
            moveDirection.y = jumpSpeed;
        }
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}
}

Unity GetComponent导致错误

关于你得到的错误,在第18行:

moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
应:

moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

你应该做的另一个修复(我假设是你以前的GetComponent错误的来源)是你在Start()方法中分配的变量没有声明。通过添加到顶部来声明它们,如下所示:

public class PlayerController : MonoBehaviour{
public float runSpeed = 6.0F;
public float jumpHeight = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
// Added
private CharacterController controller;
private Animator animController;