NetworkVariable is written to, but doesn't know its NetworkBehaviour yet.

Hello !
I am doing a Timer in my game, here is the script :

public class MatchManager : NetworkBehaviour
{
    public static readonly NetworkVariable<int> BlueScore = new NetworkVariable<int>();
    public static readonly NetworkVariable<int> OrangeScore = new NetworkVariable<int>();

    public static readonly NetworkVariable<float> TimeRemaining = new NetworkVariable<float>(120f);

    private GameObject m_Ball;
    private Transform m_BallInitialTransform;
   
    public enum Teams
    {
        Blue,
        Orange
    }

    public override void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();
        m_Ball = GameObject.FindWithTag("Ball");
        m_BallInitialTransform = m_Ball.transform;
    }

    private void Update()
    {
        if (!IsServer)
            return;

        TimeRemaining.Value -= Time.deltaTime;
    }
}

But when playing my console is flooded with warnings like this one :
NetworkVariable is written to, but doesn’t know its NetworkBehaviour yet.

Do you have any clues why it is doing that ?

I am using Unity 2022.3.1f1 LTS and Netcode For GameObjects 1.4.0

For everyone having the same problem, you should use a singleton instead of making the variables “static”.
I guess having static network variables doesn’t make much sense ^^

If only the server should change the value, you can make this:

private NetworkVariable<float> TimeRemaining = new NetworkVariable<float>(120f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
1 Like

Update() may be running before it is spawned.

In any case, this is bad practice:

TimeRemaining.Value -= Time.deltaTime;

You are making your network variable depend on a single machine’s delta time! That spells trouble! This may result in fluctuating time depending on who is updating the timer and whatever hiccups that machine may currently be experiencing.

You should be using the already synchronized time which is exposed in the NetworkManager as LocalTime and ServerTime. It is measured in ticks, as in “concrete steps” since the concept of “delta time” should not be applied when it comes to updating networked game state.

Thank you for the feedback I will update this messy code haha