I'm fairly new to Mirror with Unity and network code in general. In short, my goal is to have a gameobject
that already exists in the scene to do the following:
gameobject
on all clients and the server once the scene starts.gameobject
on only one client (this part is working).For the first part, I'm having trouble synchronizing the gameobject
between the clients. For simplicity, I have a maximum of two clients, one of which is also the host.
My issue is getting the gameobject
to synchronize between the clients and host. Here's the code I had initially using the Start()
method.
private void Start()
{
if (isServer)
{
DetermineInitialState();
}
}
[Server]
private void DetermineInitialState()
{
differenceType = Random.Range(0, 2);
if (differenceType == 0) // disable
{
RpcChangeObject();
}
}
[ClientRpc]
private void RpcChangeObject()
{
//SET CHANGE
}
This doesn't work all the time and I think it's because Start()
is firing before the server and all clients are ready. If you look at the Execution Order on the Mirror documentation, Start()
fires well before the clients and server are ready. However, if you reference the documentation on Scene Game Objects, this makes it seem that the gameobjects that are saved as part of the scene should synchronize and enable AFTER everything is loaded and ready to go, but this is not my experience.
I instead tried the following code, and it seems to work, but this is only firing on each client as they're ready:
public override void OnStartClient()
{
base.OnStartClient();
if (isServer)
{
DetermineInitialState();
}
}
Again, this seems to be working but I think it's only coincidence that each client happens to be ready when this is called. Am I missing something? Do I need to create a custom callback to check that all players have finished loading the scene before starting my DetermineInitialState()
check?
After a bit more investigation, reading documentation, and tampering, I've found the best solution is simply to implement a short timeout coroutine.
When using the Start()
MonoBehavior method, there's about a 20% chance that [ClientRpc] functions don't fire, despite the documentation stating the following:
When the Scene is loaded, all networked game objects in the Scene are disabled on both the client and the server. Then, when the Scene is fully loaded, the Network Manager automatically processes the Scene’s networked game objects, registering them all (and therefore causing them to be synchronized across clients), and enabling them, as if they were spawned at runtime.