Game won't run when built, throws errors

Title problem.

The game works just fine while in the editor and the Play button is pressed, but once built it just shoots out one error after the other.

It always gives a “NullReferenceException: Object Reference not set to an instance of an object”.

Now when looking into it, this shows up on lines of code where i am getting the components through code (the usual GameObject.Find("X").GetComponent<Y>();)

Then i tried making these variables accessible in the inspector and dragging and dropping the game objects directly onto fields. This get’s rid of the previous error, but now trying to access these variables later down the line pops up new errors.

Case in point:
I have a public int variable named Coins with an initial value of 0.

Then, another variable named CoinCounterText that contains the text box that displays the number of coins you hold. This is done using:

CoinCounterText.text = Coins.ToString()

Which ends up throwing another NullReferenceException.

I honestly don’t know where to begin solving this issue, it all works great until you build the thing.

I have uploaded the project files in the link below if anyone wants to try tackling it:
https://www.mediafire.com/file/jbrzgj5ogffs4ra/2D+Sample+Scene.rar/file

Nothing above is necessary. The answer is ALWAYS the same… ALWAYS. Doesn’t matter what you’re doing.

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 ← start here
  • Identify why it is null
  • Fix that

ALSO, two more things:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

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

and…

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

lol. good rule.

1 Like

Hi, can use this

GameObject testme = GameObject.Find("X");

if(testme != null){
    GameObject.Find("X").GetComponent<Y>();
}

Looks like cant find the “X” object, this of course may not be a full solution as you still need that “X” i assume :slight_smile:

Sometimes the above may work if is an initialization issue, e.g. “X” is initialized after the code breaks so will never happen and be always missing, but if do the above check may be initialized and work right afterwards

Don’t repeat the find!

This really should be:

testme.GetComponent<Y>();

Remember DRY … Don’t Repeat Yourself.

https://en.wikipedia.org/wiki/Don't_repeat_yourself