I keep getting null reference exception

I am currently trying to display player names on my unity game. The problem is when i use the following code below, i get a Null Reference Exception error.

LobbyController.FindLocalPlayer();
        LobbyController.UpdateLobbyName();

[code]

I tried to debug it by adding the Start() method below.

[code]
 void Start()
    {
        ControllerObject = GameObject.Find("LobbyController");
        LobbyController = ControllerObject.GetComponent<LobbyController>();  
    }
[code]

but even that hasn't worked. I checked in the inspector tab and the references aren't empty, so at this point idk what to do. Anyone know what the problem might be?

You’re sure about the line numbers, right? If you have a null reference in these lines of code:

LobbyController.FindLocalPlayer();
LobbyController.UpdateLobbyName();

That means LobbyController is null. Simple as that. You need to assign a value to it. If you add the line

LobbyController = ControllerObject.GetComponent<LobbyController>(); 

LobbyController could still be null if GetComponent is unsuccessful.

By the way, is LobbyController a component? If so do not also name your instance LobbyController. Having two things with the same name is going to cause problems.

The answer is always the same… ALWAYS!

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

ALSO THIS:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

More information: https://discussions.unity.com/t/899843/12

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.