Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

A theory about how networking works

Discussion in 'Multiplayer' started by JohnGalt, Dec 30, 2007.

  1. JohnGalt

    JohnGalt

    Joined:
    Nov 27, 2007
    Posts:
    85
    I have observed a curious effect and I want to confirm with you that my theory is correct.

    Take the Car Racing.unity scene in the Networking example.

    As is, the cars are spawned randomly. Spawn them in the same point (0,0,0), modifying CarSpawnPrefab.js.

    Start the server. Move the car far away.

    Connect a client. You will see a small glitch, like a collision... but there's nothing there, the other car is far away!

    Why happen this? Because the RPC queue system. In the new connecting client, the first thing received is the Network.Instantiate of the already created server car, which was created at (0,0,0)... then, the local car is created, at the exact same position... so, you have a collision... and just after this collision, you receive the first position update for the server car, moving it to the right position.

    Of course, this effect is hidden in the original example because it spawns cars at random positions.


    Makes sense?
     
  2. larus

    larus

    Unity Technologies

    Joined:
    Oct 12, 2007
    Posts:
    274
    Yup, thats how it works. When the client connects the server sends him all buffered RPCs, including the one which instantiates the servers car at the origin 0.0.0. The clients immediately then instantiates his own car in the origin. The servers car will be moved to his correct position as soon as a network update is received, probably a few milliseconds after instantiation, depending on latency. So this is effect is by design.

    There are simple ways to prevent this, one crude method is demonstrated (random spawn points), but one can also make sure everything is initialized before instantiating the clients own prefab. This is probably necessary for more complicated games, the new client must be brought up to speed on status of the level before he can really join himself (maybe some of the environment was destroyed, powerups are gone, etc). In the car example a simple way to do this is to make the OnNetworkLoadedLevel function yield for a short time before instantiating the clients own prefab, like 0.1 - 0.2 ms. This time just has to be a bit higher than the latency or ping time divided by 2.