GameEntity NetStatBase
This is an implementation example to networkize the StatBase<>
.
using System;
using System.Collections;
using System.Collections.Generic;
using EODE.Wonderland;
using UnityEngine;
namespace EODE.Wonderland.SimpleNet {
public abstract class NetStatBase<T> : StatBase<T>, IStat where T : IEquatable<T> {
NetVar<T> _var;
/// <summary>
/// On sync with network (emit and receive); (previous value, new value)
/// </summary>
public System.Action<T, T> OnNetUpdate = delegate { };
public override T Value {
get {
if (_var == null || _var.IsActive) {
return base.Value;
}
return _var.Value;
}
set {
if (_var == null || _var.IsActive) {
base.Value = value;
}
}
}
protected override void Awake() {
base.Awake();
if (Application.isPlaying) {
_var = this.NetVar<T>();
_var.OnHandle += v => {
OnNetUpdate.Invoke(_modifiedValue, v);
_modifiedValue = v;
};
ApplyValue(); // update value to initialize network value with the current value
}
}
public override void ApplyValue() {
if (_var == null) {
base.ApplyValue();
}
else if (_var.IsActive) {
base.ApplyValue();
if (!_var.Value.Equals(_modifiedValue)) OnNetUpdate.Invoke(_var.Value, _modifiedValue);
_var.Value = _modifiedValue;
}
}
public override bool Add(StatModifier mod) {
if (_var == null || _var.IsActive) {
return base.Add(mod);
}
return false;
}
public override bool Remove(StatModifier mod) {
if (_var == null || _var.IsActive) {
return base.Remove(mod);
}
return false;
}
}
}