I have a custom class (lets just say MyClass) that is used throughout my project. It may be in other classes that inherit from NetworkBehaviour but it may not. The problem is, MyClass contains a NetworkVariable to be synced over a Network. I have a method to manually set a NetworkBehaviour on it so that I can have MyClass on any script as long as I reference a NetworkBehaviour. Here is a simple setup:
public class MyMonoBehaviourClass : MonoBehaviour
{
public NetworkBehaviour MyNetworkBehaviourClass;
public MyClass MyClassWithNetworkVariable;
private void Awake()
{
MyClassWithNetworkVariable.SetNetworkBehaviour(MyNetworkBehaviourClass);
}
}
[Serializable]
// I don't know why but the serializer yells at me if I don't add this.
[GenerateSerializationForType(typeof(float))]
public class MyClass
{
// I have other stuff in this class but simplicity I'm just including the NetworkVariable
public NetworkVariable<float> MyVariable;
public void SetNetworkBehaviour(NetworkBehaviour networkBehaviour)
{
MyVariable = new NetworkVariable<float>();
MyVariable.Initialize(networkBehaviour);
MyVariable.OnValueChanged += OnValueChanged;
void OnValueChanged(float previousValue, float newValue)
{
Debug.Log("New value: " + newValue);
}
}
}
I thought by using the NetworkVariable.Initialize() method I could set a NetworkBehaviour to a NetworkVariable from anywhere, but it doesn’t seem to work. I even tried to have it wait to initialize until OnNetworkSpawn() was called. I don’t get any errors and the value properly updates on the host, but nothing happens at all on the client. I doesn’t notice when the value changes on the host or give any errors either.
Is it just not possible to do it this way? Does the MyMonobehaviourClass also need to be a NetworkBehaviour? Any help is appreciated.