I have a functionality that allows each connected players in a multiplayer network to go to the next player after finishing your turn. The problem is that it only works for the host/server but not the client.
I get the following error
InvalidOperationException: Client is not allowed to write to this NetworkVariable
The network variable specified above is this one here:
currentPlayerIndex.Value = nextPlayerIndex;
currentPlayerID.Value = allPlayerIDs[nextPlayerIndex];
They are found in the nextturn method highlighted below.
This is what my code does:
- The Player Manager has Network Behavior inherited that allows synchronization of all connected players and current player. It has the next turn method
public void NextTurn()
{
int nextPlayerIndex = (currentPlayerIndex.Value + 1) % allPlayerIDs.Count;
currentPlayerIndex.Value = nextPlayerIndex;
currentPlayerID.Value = allPlayerIDs[nextPlayerIndex];
Debug.Log("Next Turn : " + currentPlayerID.Value);
}
- The Player Controller (also inherits Network Behavior) is a script instantiated alongside the player when starting a client or host. It checks if it is your turn to allow the button to set active so that the client can click and allow next turn to be called.
private NetworkVariable<bool> isMyTurn = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public override void OnNetworkSpawn()
{
PlayerManager.Instance.shootBtn.onClick.AddListener(() => PlayerManager.Instance.NextTurn());
}
private void Update()
{
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.enabled = isMyTurn.Value;
if (!IsOwner) return;
Debug.Log("Current Player ID : " + currentPlayerID.Value + " : Current Player Index : " + currentPlayerIndex.Value);
if (OwnerClientId != PlayerManager.Instance.GetCurrentPlayerID())
{
isMyTurn.Value = false;
}
else if (OwnerClientId == PlayerManager.Instance.GetCurrentPlayerID())
{
isMyTurn.Value = true;
}
Debug.Log("CurrentPlayer : " + PlayerManager.Instance.GetCurrentPlayerID());
// Active to only the current Player
PlayerManager.Instance.shootBtn.interactable = isMyTurn.Value;
}
I tried to use Client RPC methods that are called from the server to allow the changes to cut across all clients but still it brings the above error.
I also tried to change the write permissions of the following variables in PlayerManager to Server but still the issue remains:
private NetworkVariable<int> currentPlayerIndex = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<ulong> currentPlayerID = new NetworkVariable<ulong>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
The write permissions are only 2 : Owner and Server.
What could be the best solution to allow the client to also update the next turn?