Here is the simple test scene:
PlayerPrefab would destroy itself after 5 seconds
public class SelfDestroy : NetworkBehaviour
{
[SerializeField] private float delay = 5f;
public static event Action<ulong> OnSelfDestroy;
public override void OnNetworkSpawn()
{
// since there is a host and a client, it's saying client would destroy self
if (IsServer && !IsOwner)
Destroy(gameObject, delay);
}
public override void OnNetworkDespawn()
{
OnSelfDestroy?.Invoke(OwnerClientId);
}
}
Test Object would respawn it after 0.5 second:
public class Respawn : NetworkBehaviour
{
[SerializeField] private GameObject playerPrefab;
public override void OnNetworkSpawn()
{
if (IsServer)
SelfDestroy.OnSelfDestroy += RespawnPlayer;
}
private void RespawnPlayer(ulong clientId)
{
Debug.Log($"Reborn player {clientId}");
StartCoroutine(RespawnPlayer(0.5f, clientId));
}
private IEnumerator RespawnPlayer(float waitTimeSeconds, ulong clientId)
{
yield return new WaitForSeconds(waitTimeSeconds);
var player = Instantiate(playerPrefab, transform.position, transform.rotation);
player.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
}
}
It also has a NetworkVariable and would call TestClientRpc every 2.5 seconds:
public class Testing : NetworkBehaviour
{
public NetworkVariable<int> count = new();
[SerializeField] private float waitTime = 2.5f;
private float timer = 2.5f;
private void Update()
{
if (!IsServer) return;
timer -= Time.deltaTime;
if (timer > 0f) return;
timer = waitTime;
TestClientRpc();
count.Value++;
}
[ClientRpc]
private void TestClientRpc()
{
if (!IsServer)
Debug.Log("Test Client");
}
}
But after PlayerPrefab respawned, the NetworkVariable wont synchronize and the TestClientRpc is never called.