Missing Reference Exception when changing scene while player object is destroyed
When I load the players into a game and then destroy a client player object and have them leave while their player object is destroyed there is a missing reference exception that endlessly runs for the client the rest of time they have the game open.
MissingReferenceException: The object of type 'Unity.Netcode.NetworkObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <84f0d810adef4e6c8deab33e4ae93f7c>:0) UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <84f0d810adef4e6c8deab33e4ae93f7c>:0) UnityEngine.Component.get_gameObject () (at <84f0d810adef4e6c8deab33e4ae93f7c>:0) Unity.Netcode.NetworkObject.UpdateForSceneChanges () (at ./Library/PackageCache/com.unity.netcode.gameobjects@f2477a6c90fe/Runtime/Core/NetworkObject.cs:3318) Unity.Netcode.NetworkObject.UpdateNetworkObjectSceneChanges () (at ./Library/PackageCache/com.unity.netcode.gameobjects@f2477a6c90fe/Runtime/Core/NetworkObject.cs:3287) Unity.Netcode.NetworkManager.NetworkUpdate (Unity.Netcode.NetworkUpdateStage updateStage) (at ./Library/PackageCache/com.unity.netcode.gameobjects@f2477a6c90fe/Runtime/Core/NetworkManager.cs:404) Unity.Netcode.NetworkUpdateLoop.RunNetworkUpdateStage (Unity.Netcode.NetworkUpdateStage updateStage) (at ./Library/PackageCache/com.unity.netcode.gameobjects@f2477a6c90fe/Runtime/Core/NetworkUpdateLoop.cs:191) Unity.Netcode.NetworkUpdateLoop+NetworkPostLateUpdate+<>c.<CreateLoopSystem>b__0_0 () (at ./Library/PackageCache/com.unity.netcode.gameobjects@f2477a6c90fe/Runtime/Core/NetworkUpdateLoop.cs:286)
- Spawn player object on a client
- Despawn client player object
- While client player object is despawned load a different scene
- See error on client every frame
Error on client runs every frame for the rest of the time while the game is open. I tried going into the NetworkObject script and adding if(this == null) return; on line 3315 (UpdateForSceneChanges) and it stops making the error. This makes me believe that it might be getting cached somewhere like the scenemanager and its not getting cleared properly when the object is destroyed on shutdown.
I except the error to not appear and the rest of the game run normally.
- OS: Windows 11
- Unity Version: 6000.0.36f1
- Netcode Version: 2.2.0
The attached game object to the NetworkObject when I was debugging it was null which is why I think it's not getting cleared properly and why the this == null is stopping the error every frame.
@Ed-Gilmour I am having a hard time replicating this issue. Could you provide additional details as to how you are handling player spawning?
Are you letting the NetworkManager handle it via the player prefab property or are you handling it via your own script?
If you are handling this via your own script, could you provide the code that is spawning and despawining the player prefab?
Also, could you provide a screenshot of your player prefab in the inspector view? I am primarily interested in the NetworkObject's settings.
@NoelStephensUnity Sure,
I'm spawning the prefab via my own script so here is the code
GameObject playerObj = Instantiate(playerPrefab, spawnTransform.position, spawnTransform.rotation);
NetworkObject playerNetObj = playerObj.GetComponent<NetworkObject>();
playerNetObj.SpawnAsPlayerObject(NetworkManager.LocalClientID, true);
Here's a screenshot of the network object, network transform, and network rigidbody 2d on the player object.
I appreciate you looking into this, let me know if there's anything else I need to show you.
@Ed-Gilmour
Are you using a distributed authority network topology?
@NoelStephensUnity I'm using Client Server, when Distributed Authority was added it defaulted my network objects to it. Is this the issue? What should I have the network objects be?
No worries... if you install the Multiplayer SDK it exposes those permissions and if you are using a client-server network topology it ignores the permissions.
If you could include the script that despawns the player prefab instance that would also help (whether you are destroying it or not).
Final questions:
- What event/logic causes the player to get despawned?
- In your initial description, you mention the client disconnecting prior to doing the scene migration (scene loading as Single mode). Was this a typo or does the client completely disconnect after its player prefab instance is destroyed?
- If so, is the order of operations like this?
- (Event occurs) Client's player prefab instance is despawned by the host/server.
- Client disconnects.
- Host transitions to a new scene.
- (If this is not the order of events could you list those out?)
- If so, is the order of operations like this?
Much appreciated on the quick responses and providing additional details. It will help me replicate the issue. If you are able, providing a replication project can expedite things. You would only need to zip up the Assets, Packages, and Project Settings folders (as long as you don't have a bunch of graphics/assets it keeps the file size pretty small).
@NoelStephensUnity Here's the code that despawns the player network object
if(IsHost)
{
NetworkObject.Despawn();
}
The player is despawned when their health goes below zero usually when hit by a projectile or when running into something.
After the client is despawned the error happens when opening the pause menu and exiting the game back to the menu from there while their player object is still destroyed (the player object will respawn after a timer so exiting before this causes the error).
As for the order of events the error occurs when the client transitions to a new scene and not the host, so it goes like this:
- Client's player prefab instance is despawned by the host/server
- Client disconnects (due to exiting the game through the pause menu)
- Client transitions to a new scene (the menu)
The project is fairly big so I can try and provide a replication project if that's sill necessary.
Are you recycling the player prefab instance? In other words, when you despawn the player prefab are you just despawning it and not destroying it?
If so and the client's player prefab is not destroyed but like disabled, then you might mark the player prefab's NetworkObject to not be destroyed with a scene load:
NetworkObject.DestroyWithScene = false;
It is being destroyed when I despawn it, so it's not going into the next scene.
While I haven't narrowed down the issue, for the time being you can disable the "Scene Migration Synchronization" for your player prefab which will prevent it from being added to the dictionary.
@Ed-Gilmour Other than the exception you are reporting, do you see any exceptions when the client's player prefab instance is despawned =or= are you destroying the associated GameObject?
The only way I can replicate this issue is if the client destroys the player prefab instance.
The player is despawned when their health goes below zero usually when hit by a projectile or when running into something.
You might verify that when this condition happens that there isn't any code that is being invoked on the client side that could cause the client-side player prefab instance to be destroyed.
@Ed-Gilmour I have put together a project that provides us with a good reference point:
There are runtime UI instructions for spawning, despawning, and then despawning and destroying (the GameObject on the client side). If you just despawn and don't destroy the client's player prefab instance, then you shouldn't run into any issues. If you despawn and then sometime shortly after destroy the client-side prefab instance's GameObject (before the client receives the despawn message from the host) then you will see the exceptions occur.
Here is a video where I run through despawning without destroying the GameObject on the client side with no exceptions and then at the end I despawn and then destroy (locally on the client) the NetworkObject's GameObject:
https://github.com/user-attachments/assets/f1be81ff-191e-43d0-8fb4-44c88d578c4e
While the exception should be handled more gracefully, if you are destroying the GameObject on the client side (before receiving the message to despawn and destroy from the host) then you would get that exception and you could run into other issues down the road even if the exception was handled more gracefully.
Take a look at the included project and let me know if this is what is happening (or something similar) in your project?
That is similar to what's happening in my project except the only error I get is on the network object. Also the client does not destroy the object, they instead use SetActive(false) to disable it until the host calls despawn to destroy and despawn the object from the host. The error occurs regardless though if the object was deactivated by the client or not. I'm also having a bit of trouble getting the replication project to work because I'm getting errors saying the player prefab is missing but I'll look into this some more when I get the chance.
Ahhh... the client side is setting the GameObject to be inactive in the scene hierarchy... so this could be a series of events that is kicked off by the combination of setting the GameObject inactive, the possibility of not processing the despawn message (or destroying the GameObject), and then upon the new scene being loaded the disabled GameObject is destroyed.... which I am going to guess that it has something to do with setting it inactive on the client side. (will look at it from this perspective)
Regarding the project, There should be no player prefab assigned. You have to manually spawn your player (hitting enter) once the host starts or a client is connected. I might have not updated the network prefab list. This version sets the player prefab instance to inactive right before invoking DespawnPlayerRpc (I do it before to prevent the camera from getting disabled).
So, hitting [Delete] will disable (set inactive) and then invoke the DespawnPlayerRpc.
I still can't replicate the issue just setting it to be inactive. 🤔
Going to see if I can whip together something to mock the reduced health issue.
Generally speaking, with a client-server topology you typically should make the changes occur on the server/host side and only reflect those changes on the client side...so my assumption is that you are setting the client-side player instance inactive only when the health drops down to zero and not also handling a pre-calculated impact based on a collision or trigger event on the client side?
Oh yeah, just to make sure... you need to just extract the zip file into a separate folder than your project and add it to UnityHub as a project for everything to work as expected.
The new project is working well! Thanks for setting that up.
So I don't think the issue is to do with the player object being disabled on the client because I tried just removing that and it still comes up with the error for the client. I do this so it's smooth for the client when a player gets destroyed, and I've checked to make sure it is getting destroyed and it definitely is.
After I've looked and tested my issue in the project I think there is a slight misunderstanding with the problem I'm having regarding the scene changes. So the error occurs when the client changes scenes. Here is the list of events that leads to the problem on the client.
- Client's player object is destroyed
- Client opens the pause menu and leaves the game while the player object is destroyed (By leaving the game I mean the client disconnects from the game and loads the menu scene)
- Error occurs on client
I could be wrong but I think in the example scene your seeing if this error occurs when the host changes scenes but this happens when the client changes scenes.
Thanks for setting up the project and helping me here, let me know if you need any more clarification.
@NoelStephensUnity I tried your solution you made here and it works well! https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/pull/3230 When do you think it'll be merged into the release version? Thanks for the help!
@NoelStephensUnity I tried your solution you made here and it works well! #3230 When do you think it'll be merged into the release version? Thanks for the help!
Once it is merged, you can expect it to be in the next update. Of course, until that happens you can always point your manifest to the develop-2.0.0 branch.
#3230 has been merged and this issue will be resolved in the next v2.2.x NGO update. Closing the issue at this time, but feel free to re-opening it if upon installing the next package update the problem persists.