I spent the past 4+ hours trying to fix a bug which initially made zero sense. I use pooling for performance, and initialize my entities (players & enemies) with the current code.
public override void OnNetworkSpawn()
{
if(IsDummy)
return;
IsDead = false;
if(!isInit) {
Callbacks.Access.OnInitialize(callbackAccessToken, this);
}
isInit = true;
if(IsOwner) {
netHealth.Value = CurStats.maxHealth;
netStamina.Value = CurStats.maxStamina;
if(!IsPlayer) {
OnNetInitializationComplete();
}
return;
}
CurStats.health = netHealth.Value;
CurStats.stamina = netStamina.Value;
netHealth.OnValueChanged += OnNetHealthChanged;
if(CurStats.health == 0u) {
_ = DelayedSyncDeath();
}
if(!IsPlayer) {
OnNetInitializationComplete();
}
}
Notice on the server, I set the netHealth to max health, and on the client I read that value. Which I believe is the correct way to do this. When playing the game normally, this all works perfectly fine. However, if the server disconnects, and the previously connected client starts a new game, the enemies spawn as dead. And SPECIFICALLY it is caused by ‘CurStats.health = netHealth.Value;’, which for some reason is stuck at zero. When I comment out that line, the game works fine again (except I can’t tell newly spawned clients that an enemy is dead).
To fix this, I call the following on awake AND despawn:
private void InitNetParams()
{
netHealth = new NetworkVariable<uint>(
readPerm: NetworkVariableReadPermission.Everyone,
writePerm: NetworkVariableWritePermission.Owner,
value: 1u
);
netStamina = new NetworkVariable<ushort>(
readPerm: NetworkVariableReadPermission.Everyone,
writePerm: NetworkVariableWritePermission.Owner,
value: 1
);
}
And I assume this is not the intended way to deal with networkvariables. My question is: when a disconnect happens, how do I force the networkvariables of the despawned objects to reset? Also, do I need to? I assume that the spawn method would always FIRST initialize the object on the server (thus resetting the hp) and THEN the clients? I am very confused as to what is causing my problem.
Some more weird things:
- It affects other networkvariables on the entity such as ones I use for animation.
- It does not affect ALL enemies, even if I killed all of them during the previous game. A handful will work normally (wtf)
- Changing NetworkConfig.SpawnTimeout didn’t work
- Using .Reset() on the variables didn’t work
- Zero errors in console