Private GameObject name Is Not Working - Please HELP

Hello guys,
Scarpis here, thank you for helping me!

Unity version: 2022.3.9f1

Please help me fix the error, i want to be able to use PRIVATE GameObject name instead of public

I want to reference a game object into a PRIVATE variable and i am getting the following error:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:22)

Here is my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
public float speed = 5.0f;
private Rigidbody playerRb;
private GameObject focalPoint;
// Start is called before the first frame update
void Start()
focalPoint = GameObject.Find("Focal Point");
playerRb = GetComponent();

// Update is called once per frame
void Update()
float verticalInput = Input.GetAxis("Vertical");
// playerRb.AddForce(Vector3.forward * verticalInput * speed); we need to rotate with the camera focal point, see below
playerRb.AddForce(focalPoint.transform.forward * verticalInput * speed);

if ( focalPoint == null)


1) Use code tags. Without them, we can't see line numbers and can only guess where your error message is pointing. Also it mutilates spacing and sometimes the code itself.

2) Odds are good that this is a problem with GameObject.Find. Try directly referencing the focal point instead. (And in general, just don't use GameObject.Find; it's terrible.)


As @StarManta pointed out.

Try using a

[SerializeField] private GameObject focalPoint;

and plug it in directly in the inspector. This is the simplest among various ways to obtain your reference.



Thank you guys, it was a space at the end of the game object name that i did not see... lol I have to be more careful next time.

[quote=“scarpis”, post:4, topic: 933581]
it was a space at the end of the game object name that i did not see… lol I have to be more careful next time.

No no no, you missed what Starmanta posted above:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

If you do NOT use GameObject.Find() you won’t care about spaces you cannot see.

More information:

More information:

In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.
If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.

1 Like