NetworkTick.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UniRx;
  5. using Sirenix.OdinInspector;
  6. using KairoEngine.Core;
  7. namespace KairoEngine.Multiplayer
  8. {
  9. [HideMonoScript]
  10. public class NetworkTick : MonoBehaviour
  11. {
  12. [LabelText("Current Tick"), ShowInInspector, ReadOnly, PropertyOrder(0)] public int tick { get; private set; }
  13. [LabelText("Refresh rate"), SuffixLabel("ms", true), PropertyOrder(1)] public int rate = 60;
  14. [PropertyOrder(2)] public string eventStreamName = "EventStream";
  15. [PropertyOrder(3)] public bool fixedCurrentTick = false;
  16. [PropertyOrder(4)] public bool autoStart = false;
  17. private bool running = false;
  18. private void Start()
  19. {
  20. if(autoStart) StartTickSystem();
  21. }
  22. private void OnDisable() => StopTickSystem();
  23. public void StartTickSystem()
  24. {
  25. running = true;
  26. tick = 0;
  27. UpdateTick();
  28. }
  29. public void StopTickSystem()
  30. {
  31. running = false;
  32. }
  33. private void UpdateTick()
  34. {
  35. if(!running) return;
  36. Timer.ExecuteRealTime(rate, () => {
  37. tick += 1;
  38. GenericEvents.Trigger($"{eventStreamName}_OnTick", tick);
  39. UpdateTick();
  40. });
  41. }
  42. public void ChangeCurrentTick(int newCurrentTick)
  43. {
  44. if(fixedCurrentTick) return;
  45. tick = newCurrentTick;
  46. }
  47. }
  48. }