Search Unity

Feature Request Update sleeping NetworkRigidbody transform for late-joining clients

Discussion in 'Netcode for GameObjects' started by CodeSmile, Oct 18, 2022.

  1. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,956
    In my tests I allow clients to join a game in progress. If I spawn physics objects on the server-side, some of them wouldn't be updated on the client-side - their position would be way off, usually on or close to the initial spawn location.

    I noticed that this only happens to rigid body objects that are sleeping on the server-side. My solution is to use the following subclass of NetworkRigidBody which, whenever a client connects and the rigid body is asleep, issues a NetworkTransform.Teleport() with the current position, rotation and scale. This reliably sends the current position to any late-joining client.

    Replace NetworkRigidBody with this NetworkRigidBodyWithLateJoinSupport script on objects where you have late-join sync issues:
    Code (CSharp):
    1. using Unity.Netcode.Components;
    2. using UnityEngine;
    3.  
    4. [DisallowMultipleComponent]
    5. public sealed class NetworkRigidBodyWithLateJoinSupport : NetworkRigidbody
    6. {
    7.     public override void OnNetworkSpawn()
    8.     {
    9.         base.OnNetworkSpawn();
    10.         if (IsServer)
    11.             NetworkManager.OnClientConnectedCallback += OnClientConnected;
    12.     }
    13.  
    14.     public override void OnNetworkDespawn()
    15.     {
    16.         base.OnNetworkDespawn();
    17.         if (IsServer)
    18.             NetworkManager.OnClientConnectedCallback -= OnClientConnected;
    19.     }
    20.  
    21.     private void OnClientConnected(ulong clientId) => SendSleepingBodyTransform();
    22.  
    23.     private void SendSleepingBodyTransform()
    24.     {
    25.         var rigidbody = GetComponent<Rigidbody>();
    26.         if (rigidbody.IsSleeping())
    27.         {
    28.             var netTransform = GetComponent<NetworkTransform>();
    29.             netTransform.Teleport(rigidbody.position, rigidbody.rotation, transform.localScale);
    30.         }
    31.     }
    32. }
    33.  
    I think this should be handled by NetworkRigidBody and this late-join behaviour made optional with a flag.
     
    Last edited: Oct 18, 2022