NullReferenceException in Urity RPG Tutorial Video 1

Updated on November 8, 2017 in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
5 on November 6, 2017

Hi,

I’ve been following along with your wonderful video but I’ve run into a problem. In the player controller script it gives me a NullReferenceException error of object reference not set to an instance of an object error. Here’s the code: 

public class PlayerController : MonoBehaviour {
public LayerMask movementMask;
Camera cam;
 PlayerMotor motor;
// Use this for initialization
 void Start () {
 cam = Camera.main;
 motor = GetComponent<PlayerMotor>();
 }
 // Update is called once per frame
 void Update () {
 if (Input.GetMouseButtonDown(0))
 {
 Ray ray = cam.ScreenPointToRay(Input.mousePosition);
 RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100, movementMask))
 {
 motor.MoveToPoint(hit.point);
 // Move player to what we hit
// Stop focusing any objects
 }
 }
 }
}

I have already trying the suggestion of tagging the camera as the main camera.  Please help.

Thanks,

Heleen

  • Liked by
Reply
1 on November 6, 2017

The code itself seems legit. But what I need to know is what exactly gives you that NullReferenceException error, in what line and which object?

It could be 3 things, the LayerMask, the Camera or the PlayerMotor.

 

on November 7, 2017

Thanks for the fast response.  The error has the NullException in the PlayerController Script in the Update method. It says @ Asset/PlayerController.cs:28.  When I use the debug feature that replaces the Inspector and I select the Player; the cam spot shows the main camera; but the Motor spot shows None. For reference here is my PlayerMotor script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class PlayerMotor : MonoBehaviour {
NavMeshAgent agent;
 // Use this for initialization
 void Start () {
 agent = GetComponent<NavMeshAgent>();
 }
 public void MoveToPoint(Vector3 point) {
 agent.SetDestination(point);
 }
}

Thanks for your help.

Heleen

Show more replies
  • Liked by
Reply
Cancel
2 on November 7, 2017

Do you have both scripts at the same gameObject? Because if not, the function in PlayerController will not work:

motor = GetComponent<PlayerMotor>();

try instead:

motor = GetComponentInChildren<PlayerMotor>(true);

 

on November 7, 2017

Thank you! Thank you! Thank you!  I can’t believe I forgot to attach the script to the player.  Everything works wonderfully now. 

Heleen

Helpful
on November 8, 2017

You’re welcome. Sometimes it’s the easiest thing what don’t come into your mind.

Just as I did some seconds ago 🙂

 

Show more replies
  • Liked by
Reply
Cancel