Globals
Use Globals
to share a variable outside a scene. A Global
contains values of each clients. Each global has a unique id, you can define it by using a static class in your project.
public static class NetGlobalIds {
public const ushort ValidateButtonTest = 1;
public const ushort Test2 = 2;
public const ushort Test3 = 3;
public const ushort Test4 = 4;
}
Globals are not safe in Host mode
Values and aliases
// SETTERS
_global.Set(value);
_global.Value = value;
// GETTERS
_global.Local; // the local value
_global.Value; // alias of Local
_global.Values; // Dictionary<int PeerId, A value>
Example (interface)
Image becomes green when all players tick the checkbox.
using EODE.Wonderland;
using EODE.Wonderland.SimpleNet;
using UnityEngine;
public class SimpleNetTestGlobal : MonoBehaviour {
public UnityEngine.UI.Image Image;
public UnityEngine.UI.Toggle Toggle;
NetGlobal<bool> _validate;
void Start() {
_validate = NetGlobal.Create<bool>(NetGlobalIds.ValidateButtonTest, false); // second argument is the default value
_validate.OnUpdate += () => {
var off = _validate.Values.FirstOrNull(kv => !kv.Value);
Image.color = off.HasValue ? Color.red : Color.green;
};
Toggle.onValueChanged.AddListener(_validate.Set);
}
}
Example (in game button)
using UnityEngine;
using EODE.Wonderland.SimpleNet;
public class GlobalButton : MonoBehaviour {
public Renderer Renderer;
public Material MatOff;
public Material MatOn;
NetGlobal<bool> _on;
void Start() {
_on = NetGlobal.Create<bool>(12, false); // second argument is the default value
_on.OnUpdate += () => {
Debug.Log("Global = "+string.Join(", ", _on.Values));
var off = _on.Values.FirstOrNull(kv => !kv.Value);
if (off.HasValue) Renderer.material = MatOff;
else Renderer.material = MatOn;
};
}
void OnTriggerEnter(Collider collider) {
// Unlike Shared variables, we use IsEmitter in place of IsActive here, because clients emit Globals in host mode
if (collider.GetComponent<NetworkedObject>().IsEmitter) {
_on.Value = true;
}
}
void OnTriggerExit(Collider collider) {
if (collider.GetComponent<NetworkedObject>().IsEmitter) {
_on.Value = false;
}
}
}