Bizarre NullReferenceException like no other
If anyone has any idea what could be causing a problem like this it would be great. It has completely stumped both me and my coworker. This project is a server authoritative networked game on Unity 5.6.2p2.
After the first player connects the player's client is able to spawn and initialize the player prefab, including the playercontroller, inventory, and UI.
When the second player connects the player prefab is instantiated and the playercontroller's OnStartLocalPlayer executes in which the UI is instantiated and a reference to the UI monobehaviour is assigned. At this point the reference to the UI is valid.
This is where it gets weird. Only on the second player that connects (and every player after the first), the reference (playerUI) to the UI appears to be null every other frame. The UI is never destroyed and it is always visible in the scene hierarchy. The only time that playerUI is being assigned to is in the original OnStartLocalPlayer function.
Creating a reference to the UI in a different script yields the same results. BUT I am able to get a reference to the UI every frame if I search for the monobehaviour type in the scene (using FindObjectOfType) every other frame when it is null.
Sorry if my writing is unclear. I'd be happy to clarify/elaborate further if anyone thinks they may have some insight.
Put a Debug.Log in your OnStartLocalPlayer function. $$anonymous$$ake absolutely sure it's only being called when it's supposed to.
Thanks for the response!
This was one of the first things I tested, OnStartLocalPlayer is only called once after the player's initial player prefab instantiation.
Answer by joshuahaag · Oct 03, 2017 at 05:52 PM
I've managed to solve the problem by moving the initialization of the inventory from OnStartClient to a public Init function. So in the playercontroller's OnStartLocalPlayer it looks like this now:
playerUI = Instantiate(prefab_PlayerUI)
inventory.Init()
playerUI.Init(this)
Though I'm not exactly sure how this fixed the problem considering the first player to connect was able to initialize and use everything correctly but at this point I'm not going to question it.
I'd still like to hear anyone's ideas, just out of pure curiosity :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612140204im_/https://answers.unity.com/themes/thub/images/avi.jpg)