Unity-Multiplayer: Use Netcode in local Scenes, that are not synced by the NetworkManager (but use the NetworkObject of the client)
I spend this week figuring out, how to make a Unity-Netcode app. Normally Unity-Netcode is used, to have all clients completely in sync by the server. Makes sense: When doing multiplayer, all events should be the same for everyone.
But at the app we are currently building (an XR-experience for the Quest 3), we need to load some scenes locally only on one client at a time. This is possible, just by not using the NetworkManager.SceneManager.LoadScene method, but by triggering a normal SceneManager.LoadScene on the client itself. Note this detail: The new scene must be loaded as a additive-scene (so that the NetworkManager on the client does not get unloaded).
Code for loading the scene on the client:
[ClientRpc]
void LoadSceneClientRpc()
{
if (!IsServer && IsOwner)
{
SceneManager.LoadScene("LoadThisScene", LoadSceneMode.Additive);
}
}
Very straightforward.
But how to send events now back to the server?
This is fine and works. Note, that this scene got loaded without beeing observed by the NetworkManager. In our case, we need to send events and scores now from the additive loaded scene back to the server. But how? This scene does not have a NetworkObject, that would be capable of doing so.
I also tried a lot of tricks, to reference the GameObject on the client, that loaded this additional loaded scene. But no matter what I tried, I got an error: “This GameObject is not allowed to write something to the server”.
Here I share now one line of code, that would have saved me four days of work:
NetworkManager.LocalClient.PlayerObject.GetComponent<MyComponentScriptToCall>().MyCustomCallServerRpc();
In that way, you can ALWAYS get the current LocalClient, that can send stuff to the server. I would say, this could written very clearly and prominent in the Unity-Docs. So it is now a pleasure for me, to share this with you!
More Indie-Game-Dev stuff
I write more about indie-game-dev on Medium. Read for example this article How to overcome Indie-Game-Devs writers block.