I finished the lesson for “Namespaces To See Dependencies” for the “2019 RPG Core Combat Creator” course, but now when I click to move my character around, I get the following error message in the console:
“NullReferenceException: Object reference not set to an instance of an object
RPG.Control.PlayerController.MoveToCursor () (at Assets/Scripts/Control/PlayerController.cs:23)
RPG.Control.PlayerController.Update () (at Assets/Scripts/Control/PlayerController.cs:12)”
The console spits 5 or so of these errors whenever I click. It doesn’t affect gameplay, thankfully, but I don’t want it to be a problem further down the line, so I’m trying to fix it now.
Here’s my code for the PlayerController script:
using RPG.Movement;
using UnityEngine;
namespace RPG.Control
{
public class PlayerController : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButton(0))
{
MoveToCursor();
}
}
private void MoveToCursor()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit Hit;
bool HasHit = Physics.Raycast(ray, out Hit);
if (HasHit)
{
GetComponent<Mover>().MoveTo(Hit.point);
}
}
}
}
And here’s the code for the Mover script, in case it’s related:
using UnityEngine;
using UnityEngine.AI;
namespace RPG.Movement
{
public class Mover : MonoBehaviour
{
// [SerializeField] Transform target;
void Update()
{
UpdateAnimator();
}
public void MoveTo(Vector3 destination)
{
GetComponent<NavMeshAgent>().destination = destination;
}
private void UpdateAnimator()
{
Vector3 velocity = GetComponent<NavMeshAgent>().velocity;
Vector3 LocalVelocity = transform.InverseTransformDirection(velocity);
float speed = LocalVelocity.z;
GetComponent<Animator>().SetFloat("ForwardSpeed", speed);
}
}
}
Please help.