Hi!
I’m using the script below to move the player and check collisions (following the Unity 2D Roguelike game tutorial), but when I click the defined key to move, I receive the error:
NullReferenceException: Object reference not set to an instance of an object
MoveObject.CheckMove (Single x, Single y, Single z, UnityEngine.RaycastHit& _hit) (at Assets/MoveObject.cs:21)
MoveObject.Movement (Single x, Single y, Single z) (at Assets/MoveObject.cs:50)
Player.Update () (at Assets/Player.cs:26)
Here is my code on the MoveObject.cs.
using UnityEngine;
using System.Collections;
public abstract class MoveObject : MonoBehaviour
{
public float speed = 0.1f;
public LayerMask blockingLayer;
private BoxCollider boxCollider;
private Rigidbody rb;
protected void Start()
{
speed = 1f / speed;
boxCollider = GetComponent<BoxCollider>();
rb = GetComponent<Rigidbody>();
}
protected bool CheckMove(float x, float y, float z, out RaycastHit hit)
{
Vector3 pos = transform.position;
Vector3 targetPos = pos + new Vector3(x, y, z);
boxCollider.enabled = false;
Physics.Linecast(pos, targetPos, out hit, blockingLayer);
boxCollider.enabled = true;
if (_hit.transform == null)
{
StartCoroutine(Move(targetPos));
return true;
}
else
{
return false;
}
}
public IEnumerator Move(Vector3 targetPos)
{
float remainingDistance = (transform.position - targetPos).sqrMagnitude;
while (remainingDistance > float.Epsilon)
{
Vector3 newPos = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
rb.MovePosition(newPos);
remainingDistance = (transform.position - targetPos).sqrMagnitude;
yield return null;
}
}
protected virtual void Movement(float x, float y, float z)
{
RaycastHit hit;
Debug.Log(x + " " + y + " " + z); //Checking the values
bool canMove = CheckMove(x, y, z, out hit);
if (hit.transform == null)
{
return;
}
}
}
And the Player.cs:
public class Player : MoveObject
{
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("w") || Input.GetKeyDown("up"))
{
Movement(1f, 0f, 0f);
}
else if (Input.GetKeyDown("s") || Input.GetKeyDown("down"))
{
Movement(-1f, 0f, 0f);
}
else if (Input.GetKeyDown("d") || Input.GetKeyDown("right"))
{
Movement(0f, 0f, 1f);
}
else if (Input.GetKeyDown("a") || Input.GetKeyDown("left"))
{
Movement(0f, 0f, -1f);
}
}
}
What I don’t get is why I’m having this error, since when cheking the x, y and z values with Debug.Log, they do show on the console.
Thanks.