对象引用未设置为对象的实例.团结



我真的是unity的新手,我正在尝试在不同的文件中制作一个具有不同状态的PlayerController。

这是迄今为止的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private PlayerState currentState;
void Start()
{
currentState = new PlayerIdle(this);
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
currentState.OnStateUpdate();
}
public void ChangeState(PlayerState newState)
{
currentState.OnStateExit();
currentState = newState;
newState.OnStateEnter();
}
}

我该怎么解决这个问题?

编辑:这是PlayerIdle代码,应该会给我错误。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerIdle : PlayerState
{
public CharacterController controller;
public Transform cam;
public GameObject player = GameObject.Find("Player");
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3;
public float rotationSpeed;
float x;
float z;
public Transform groundCheck = GameObject.Find("groundCheck").transform;
public float groundDistance = 0.4f;
public LayerMask groundMask;
[SerializeField] Vector3 velocity;
public bool isGrounded;
public float turnSmoothTime = 1f;
float turnSmoothVelocity;
public PlayerIdle(PlayerController playerController) : base(playerController)
{
this.playerController = playerController;
}
public override void OnStateEnter()
{
}
public override void OnStateExit()
{
}

public override void OnStateUpdate()
{
x = Input.GetAxisRaw("Horizontal");
z = Input.GetAxis("Vertical");
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
velocity = player.transform.TransformDirection(Vector3.forward) * speed * z + new Vector3(0f, velocity.y, 0f); ;
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}

velocity.y += gravity * Time.deltaTime;
player.transform.Rotate(new Vector3(0f, x * rotationSpeed, 0f));
controller.Move(velocity * Time.deltaTime);
}

}

任何帮助都将不胜感激:)

此外,我发现这被称为状态机,如果这有帮助的话。

错误表明该行中的某些内容为null。唯一可以为null的是CurrentState变量。可能当您在Start()方法中为其指定新PlayerIdle(this)的值时,该值为null。如果你能弄清楚它为空的原因,你可以修复它,但如果你仍然有问题,你可以包括PlayerIdle()代码。建议在Start()的末尾插入一个print(currentState),以了解它是否真的为null。此外,还可以在Update()方法中插入一个print(new PlayerIdel(this)),以了解即使在更新过程中它是否仍然为null。

似乎在start方法之前调用了update方法(我仍然不理解),所以解决方案只是在currentState.OnStateUpdate()之前添加一个if语句;说";如果(currentState!=null)";

相关内容

  • 没有找到相关文章

最新更新