How to trigger NetworkVariable.OnValueChange for P1 when P2 joins the game as Client?
Hi,
I'm trying to learn MLAPI. I have two players (P1 and P2).
Once Player spawns, it:
Asks server to generate random color
The color is assigned into NetworkVariable
Event NetworkVariable.OnValueChanged is triggered which assigns the color to the player's renderer.
How it works when code below is implemented:
P1 HOSTS the game.
P1 Gets random color successfully.
P2 JOINS the game.
P1 Gets information about P1 generated color succesfully.
P2 Gets information about P1 color unsuccessfully.
P2 Gets grandom color successfully.
This means that NetworkVariable.OnValueChanged is never triggered on P2 game for P1. How to achieve this with best practices of Unity MLAPI?
Working workaround (but feels weird to be best practice) - I added a bool check to OnValueChanged to check if "isSpawned" - it applies the color to the renderer of a player only if the player is already spawned in the game.
Anything helps!
using Unity.Netcode;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Player
{
public class Player : NetworkBehaviour
{
[SerializeField] private NetworkVariable<Color> m_playerColor = new NetworkVariable<Color>();
[SerializeField] private SpriteRenderer m_spriteRenderer;
[SerializeField] private bool m_triggerRngColor;
private bool m_isSpawned;
private void OnEnable()
{
m_playerColor.OnValueChanged += OnColorChanged;
}
private void OnDisable()
{
m_playerColor.OnValueChanged -= OnColorChanged;
}
private void OnColorChanged(Color previousValue, Color newValue)
{
m_spriteRenderer.color = m_playerColor.Value;
}
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (IsServer)
{
m_playerColor.Value = GenerateColor();
m_spriteRenderer.color = m_playerColor.Value;
}
}
private Color GenerateColor()
{
var colors = new Color[] {Color.black, Color.blue, Color.red, Color.green, Color.cyan, Color.magenta, };
var color = colors[Random.Range(0, colors.Length)];
return color;
}
}