I am spawning a NetworkObject with client ownership, and trying to subscribe to changes to a NetworkVariable (for the player name), but the client-machine instances are not receiving the OnValueChanged callbacks.
The object is spawned correctly with the right ownership.
The NetworkVariable is set to owner write permissions and everyone read permission.
The NetworkVariable value gets updated on all instances and I can read them on each client.
But the client does not receive the callback.
I am trying to create a UI (not a networkobject) where players details are shown, but players can change their details and these get live propagated to all machines. The OnValueChanged callback is very helpful to update the UI only when there are new values to show.
Any clues why?
public class KingdomsNetworkPlayer : NetworkBehaviour
{
#region vars
private NetworkVariable<FixedString64Bytes> m_playerName = new NetworkVariable<FixedString64Bytes>(new FixedString64Bytes("New Player"), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public string PlayerName => m_playerName.Value.ToString();
public void SetPlayerName(string newName)
{
var newValue = new FixedString64Bytes(newName);
if(newValue != m_playerName.Value) m_playerName.Value = newValue;
}
private NetworkVariable<int> m_playerNum = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public int PlayerNum => m_playerNum.Value;
public void SetPlayerNum(int num) => m_playerNum.Value = num;
#endregion
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
m_playerName.OnValueChanged += OnPlayerNameChangedEvent;
m_playerNum.OnValueChanged += OnPlayerNumChangedEvent;
if (IsOwner)
{
KingdomsApp.Inst.ReadyToLaunchLobby(); //NB: This just triggers a lobby-style UI
if (IsHost)
{
m_playerNum.Value = 1;
}
else
{
m_playerNum.Value = 2;
}
//NB: This is the client-side singleton that updates a local list of player entities
KingdomsApp.Inst.playerManager.UpdateLocalAndNetworkPlayers(this, true);
}
else
{
KingdomsApp.Inst.playerManager.UpdateLocalAndNetworkPlayers(this, false);
}
}
public override void OnNetworkDespawn()
{
base.OnNetworkDespawn();
m_playerName.OnValueChanged -= OnPlayerNameChangedEvent;
m_playerNum.OnValueChanged -= OnPlayerNumChangedEvent;
}
private void OnPlayerNameChangedEvent(FixedString64Bytes previousValue, FixedString64Bytes newValue)
{
KingdomsApp.Inst.playerManager.UpdateLocalAndNetworkPlayers(this,IsOwner);
}
private void OnPlayerNumChangedEvent(int previousValue, int newValue)
{
KingdomsApp.Inst.playerManager.UpdateLocalAndNetworkPlayers(this,IsOwner);
}
}