How to fix the NullReferenceException in your script?

Hi there.This is my first post as up till now i have been able to figure out my mistakes or find another way to approach the problem.But this time I am stuck and would like some advice and help.

I checked my scripts multiple times and found no flaws.Also checked that all game objects that are called are in the correct poistions and that the correct scipt is attached to them.And the game works but when i get hit by an enemy it says that there is NullReferenceException.But I can’t seem to find where the NullReferenceException is located in my script.
(By the way i have encountered similar problems with NullReferenceException and have been able to fix them till now)

GameConroller is the script that contains the variable lives.I use the following to call a function from another script in order to subtract lives and respwan the player once hit.`

GameController.lives -= 1;

if(GameController.lives > 0)

{

gameObject.Find(“GameController”).GetComponent(GameController).Respawn();

}`

It says that my nullreference exception occurs in the if statement above.
This statement is inside an OnTriggerEnter function so that when the enemy bullet hits the player the player dies.
Respawn is the function that is being called from other script and inside that function I have the following :
Instantiate(Player, Vector3(-0.1, 0.5, -4), transform.rotation);

I know that unity is telling that the problem is inside my if statement but i just can’t see it.
All help and advice is welcome.

If I understand you, it is the gameObject.Find statement that has a null exception? If so then there are several possibilities, the Find is returning null, the game object returned doesn’t actually have a GameController component. Break each of these up into separate lines might help it identify which one is failing.

My personal guess is that Find(“GameController”) is returning a null because you don’t actually have an object named GameController, but rather a GameController script added to some object. But again without seeing your entire project and hierarchy it is difficult to tell you exactly what is happening.

Replace the find line with

 GameObject go = gameObject.Find("GameController");
 if (go == null)
 { 
   Debug.Log("GameObject is null, problem found");
   return;
 } 
 GameController gc = go.GetComponent< GameController >();
 if (gc == null)
 { 
   Debug.Log("gamecontroller is null, problem found");
   return;
 }

 gc.Respawn();

After writing this I usually use the GetComponent< TYPE >() to return the component. Try that first

 gameObject.Find("GameController").GetComponent< GameController >().Respawn();

I just found the problem.I simply deleted the previous empty object that had the GameController script attached to it and then made a new one.This seemed to fix the issue I had.Thanks for the help :smiley: