I am following the tutorial for lesson 4.1 on unity learn. My scripts have been exactly the same as the one that is shown in the tutorial except that my one does not work. The console window keeps telling me: NullReferenceException: Object reference not set to an instance of an object PlayerController.Update () (at Assets/Scripts/PlayerController.cs:23) What is wrong? using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { private Rigidbody playerRb; private GameObject focalPoint; public float speed = 5.0f; // Start is called before the first frame update void Start() { playerRb = GetComponent<Rigidbody>(); focalPoint = GameObject.Find("Focal Point"); } // Update is called once per frame void Update() { float forwardInput = Input.GetAxis("Vertical"); playerRb.AddForce(forwardInput * speed * focalPoint.transform.forward); } }
First of all, please use the code-button to insert code so it gets formatted and more readable. Regarding your error it seems you forgot to add a ridgidbody component to your PlayerController gameobject, so when Start() is executed the GetComponent can't find a ridgidbody. Or you don't have a gameobject called "Focal Point" in the scene or the spelling is a bit different (maybe you forgot the space between the words?).
You should avoid using GameObject.Find(). I know it's common for the tutorials to point to it but it's a very common cause of problems because it's easy to make a mistake on one of the steps to make it work properly. Instead if it's an object that will always exist in the scene just set focalPoint to public and link it up in the Inspector.
The important thing here is that your code can be exactly correct, but something your code interacts with can be wrong! In this case, if the script fails to find the thing it's looking for (because it doesn't exist at all, most likely), it'll wind up erroring out.
It's always the same answer and it never requires a forum post. Here's why: How to fix a NullReferenceException error https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/ Three steps to success: - Identify what is null <-- any other action taken before this step is WASTED TIME - Identify why it is null - Fix that
I'm sorry and thank you all for help. As usual, taking a short break does a good job of solving the problem. I made a space in "FocalPoint". That's why it happened.
That's a big problem with "magic strings" -- it's super easy to get them wrong! Assuming the target exists before the game starts, it might be more reliable to just make focalPoint a public variable and to assign it in the inspector.
If the target does not exist at the start and you must find it for any reason then you can also use find by tag. And instead of using the name of the tag everywhere, you can have a helper class with static strings for all your tags so you can type: GameObject.FindByTag(TagHelper.PLAYER_TAG).