【发布时间】:2019-12-05 07:37:23
【问题描述】:
我一直在尝试制作一个脚本,但是由于某种原因,我的 Rigidbody 变量拒绝存在于范围之外。它给我的错误读出:NullReferenceException: Object reference not set to an instance of an object VelocityBasedPlayerMovement.FixedUpdate () (at Assets/Scripts/VelocityBasedPlayerMovement.cs:80)
上一行的错误非常相似。
NullReferenceException: Object reference not set to an instance of an object
VelocityBasedPlayerMovement.Update () (at Assets/Scripts/VelocityBasedPlayerMovement.cs:29)
这是我的代码。注意 Rigidbody 已设置,对象确实有一个刚体,因为第一个 debug.log 显示了它所在的对象的名称。但是这两行拒绝工作
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VelocityBasedPlayerMovement : MonoBehaviour
{
private Rigidbody rb;
public int maxSpeed;
public float speedMult;
public float acceleration;
public float decelleration;
private bool keyNotPressed = false;
private Vector3 velocity = new Vector3(0, 0, 0);
private Vector3 temp = new Vector3(0, 0, 0);
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody>();
/*THIS IS FINE
Debug.Log("Rigidbody attached to: "+rb.gameObject.name);
*/
if(rb = null)
{
Debug.LogError("Could not find Rigid Body!\n" + this.name);
}
}
// Update is called once per frame
void Update()
{
/*THIS IS AN ERROR
Debug.Log("Rigidbody attached to: " + rb.gameObject.name);
*/
// TODO Make these proper controls instead of static keys
if (Input.GetKeyDown(KeyCode.W))
{
keyNotPressed = false;
temp += this.transform.forward;
}
if (Input.GetKeyDown(KeyCode.S))
{
keyNotPressed = false;
temp += -this.transform.forward;
}
if (Input.GetKeyDown(KeyCode.A))
{
keyNotPressed = false;
temp += -this.transform.right;
}
if (Input.GetKeyDown(KeyCode.D))
{
keyNotPressed = false;
temp += this.transform.right;
}
else if(Input.GetKeyDown(KeyCode.None))
{
keyNotPressed = true;
temp = new Vector3(0, 0, 0);
}
temp = temp.normalized;
}
void FixedUpdate()
{
if (!keyNotPressed)
{
if ((velocity + temp).magnitude > maxSpeed)
{
velocity = temp;
Debug.LogWarning("Player is above max speed!\n" + (velocity + temp).magnitude);
}
else
{
velocity = temp*acceleration;
}
}
else
{
velocity -= velocity * decelleration;
}
/*Error here too
rb.velocity = velocity;
*/
}
}
是的,我知道代码不应该按预期工作,但我正在努力。当刚体拒绝正确设置时,很难测试它
【问题讨论】: