Shared mode: how to ensure only a single object is spawned, and one client always has authority
I'm trying to implement a networked scene loader in Shared mode. Only one of these can ever exist, with the current shared master client having authority over it. How can I achieve this?
Here is what I am doing now:
- When OnConnectedToServer() fires and we are the master client -- and there is no other NetworkSceneManager object in the scene -- spawn our NetworkSceneManager object.
This seems like it could be prone to a race condition if the master client happens to disconnect at almost the same time that a new client connects and is selected as master to replace it. In that case, I am not sure that the existing NetworkSceneManager object will be visible to the connecting client when OnConnectedToServer fires.
It seems like I need to know when it is safe to query for existing objects before spawning the new one. The host/client network scene loading example does something I don't understand: it effectively checks in the object's Spawn() method whether another of the same object already exists and then de-spawns if so. I think this only works because the host has state authority, so it will always despawn "newer" objects.
In Shared mode, the situation is much trickier.
There is potentially a second way: in Spawned(), check to see whether multiple instances of the same object exist and only despawn the one we have authority over. Seems a bit hacky.
The master client spawns this single object somehow. Ok. How do I ensure state authority is properly transferred when that client disconnects? I don't want to end up in a state where the new master fails to realize it momentarily lacks state authority over the object and tries to set some network properties on it (e.g., tries to load a scene). What is the pattern commonly used here?
The obvious solution is messy: have an IsMaster property that checks whether we are the shared master and whether we have state authority over all of the singleton objects we need. Is there a better mechanism?