using UnityEngine; using Normal.Realtime; using System; using System.Linq; [RealtimeModel(true)] public partial class NetRPCHandlerModel { [RealtimeProperty(1, true, true)] private int _trigger; [RealtimeProperty(2, true, true)] private string _args; public void FireEvent(string args) { this.args = args; this.trigger++; } } public class NetRPCHandler : RealtimeComponent { [SerializeField] private bool canOnlyBeCalledByOwner = true; /// /// Invokes when an event is recieved. Also sends across the parameters. /// public Action OnEventRecieved; bool canRecieveEvents; float startDelayBeforeCanRecieve = 0.25f; Realtime rt; RealtimeView rtView; private void Awake() { canRecieveEvents = false; rtView = realtimeView; if (rtView == null) { rtView = GetComponentInParent(); } rt = realtime; if (rt == null) { rt = FindFirstObjectByType(); } } private void Start() { if (rtView.isSceneView) { rt.didConnectToRoom += r => { Invoke("Initialise", startDelayBeforeCanRecieve); }; } if (rtView.isPrefabView) { Invoke("Initialise", startDelayBeforeCanRecieve); } } private void Model_triggerDidChange(NetRPCHandlerModel model, int value) { _OnEventRecieved(model.args); } void Initialise() { Debug.Log("Initialised RPC handler on object " + gameObject.name); canRecieveEvents = true; model.triggerDidChange += Model_triggerDidChange; } /// /// Fires an event with no additional parameters. /// public void FireEvent() { FireEvent(null); } /// /// Sends an event across the network with parameters. Events are detected by the value "trigger" on the RealtimeModel changing. /// /// /// Additional parameters for the event. /// public void FireEvent(string args) { var rv = rtView; if (rv == null) return; // how can it be null what the Fuck if (rv.isOwnedRemotelySelf && canOnlyBeCalledByOwner) return; Debug.Log($"[NetRPCHandler] Firing event on {gameObject.name} with args {args}", this); model.FireEvent(args); } public void _OnEventRecieved(string args) { if (!canRecieveEvents) return; Debug.Log($"[NetRPCHandler] Recieved event on {gameObject.name} with args {args}", this); OnEventRecieved.Invoke(args); } }