Search Unity

MLAPI - networked variables in Game Manager

Discussion in 'Netcode for GameObjects' started by wazniak96, Apr 8, 2021.

  1. wazniak96

    wazniak96

    Joined:
    Apr 8, 2021
    Posts:
    1
    Hi,

    I'm trying to create a simple multiplayer game in Unity. I decided to use MLAPI but I have some smaller and bigger problems due to lack of informations about this new module.

    In order to create a game I need to set some Networked variables that will be synchronized across all players to keep some world related informations (eg. whose turn is currently). To do that I was trying to use NetworkedVariable in my custom NetworkManager but without results. Same when I was trying to do that in my GameManager.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.Networking;
    4. using UnityEngine.Networking.Match;
    5. using MLAPI;
    6. using MLAPI.NetworkVariable;
    7.  
    8. public class MyNetworkManager : NetworkManager
    9. {
    10.  
    11.     NetworkVariableInt test = new NetworkVariableInt(new NetworkVariableSettings { WritePermission = NetworkVariablePermission.Everyone }, 10);
    12.  
    13.     public void PrintValue()
    14.     {
    15.         Debug.Log(test.Value);
    16.     }
    17.  
    18.     public void Increase()
    19.     {
    20.         test.Value = test.Value + 1;
    21.     }
    22. }
    23.  
    Can anyone point me to the correct approach to solve this problem?
    I was looking for some examples and tutorials but i found only informations about creating players. That doesn't solve my problem.
     
  2. Qazuro

    Qazuro

    Joined:
    Aug 4, 2020
    Posts:
    9
    You have to sync variables with RPCs
    here is a video on how to do that:


    here's some code I wrote that does it with a string

    Code (CSharp):
    1. [SerializeField]
    2.     Text nameText;
    3.  
    4.     public NetworkVariableString playerName = new NetworkVariableString();
    5.  
    6. [ServerRpc]
    7.     public void UpateTheNameServerRpc(string newName)
    8.     {
    9.         playerName.Value = newName;
    10.     }
    11.  
    12.     private void OnEnable()
    13.     {
    14.         playerName.OnValueChanged += OnNameChanged;
    15.     }
    16.     private void OnDisable()
    17.     {
    18.         playerName.OnValueChanged -= OnNameChanged;
    19.     }
    20.     void OnNameChanged(string oldName,string newName)
    21.     {
    22.         if (!IsClient) { return; }
    23.         nameText.text = newName;
    24.     }
    25.