1

I'm making an online multiplayer game with Unity and MLAPI. I wrote the script below and placed it in my scene, meaning each client and server should run it when a scene loads. The server is supposed to set the variable to 1, but it's not changing on the clients!

using UnityEngine;
using MLAPI;
using MLAPI.Messaging;
using MLAPI.NetworkVariable;

public class TestNetwork : NetworkBehaviour
{
    public NetworkVariableInt Test = new NetworkVariableInt(-1);

    void Start() {
        if (!NetworkManager.Singleton.IsServer) return;
        Test.Value = 1;
    }

    void Update() {
        Debug.Log($"{Test.Value}");
    }
}
xjcl
  • 12,848
  • 6
  • 67
  • 89

2 Answers2

1

If you have a NetworkVariable<T> not syncing, it could be any of the following:

  • Make sure your class is inheriting from NetworkBehaviour, not MonoBehaviour.

  • Make sure the GameObject your script is attached to also has a NetworkObject component:

    enter image description here

    If not, click on "Add Component" and add the NetworkObject script.

  • Local object references just cannot be synced. Try to make them NetworkObjects or sync them as ID numbers instead. (Unlike the other 2, this should print error logs.)

xjcl
  • 12,848
  • 6
  • 67
  • 89
  • Isn't the first and last point already fulfilled in your question anyway? It **is** a `NetworkBehaviour` and the value is an `int` ..... – derHugo May 26 '21 at 12:03
  • Yeah I just wanted to put it here as general reference. I made all 3 of the mistakes before, in the example it was using MonoBehaviour by accident, and I just changed it at the last second to be correct so people wouldn't copy wrong code from the internet. – xjcl May 26 '21 at 12:08
  • well in general the issue code should go into the question, the answer code into the answer ;) If people copy not working code from a question it's their own fault anyway ... and in general if people simply copy&paste code without understanding it it is also their own fault ;) – derHugo May 26 '21 at 12:12
0

The MLAPI is changing fast and this might not be relevant anymore, but also make sure you set the NetworkVariable permissions correctly:

NetworkVariable<int> Test = new NetworkVariable<int>(-1);

private void Awake() {
    Test.Settings.ReadPermissions = NetworkVariablePermission.Everyone;
    Test.Settings.WritePermissions = NetworkVariablePermission.Everyone;
}
Rom
  • 426
  • 5
  • 11
  • For future readers, you should probably not allow everyone to change the network variable of every client, therefore NetworkVariablePermission for Write should be set to server, or even owner if you architecture is peer 2 peer. – Eric Dec 05 '22 at 22:45