Pro_Unit

Events

Nov 30th, 2020
402
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections.Generic;
  2.  
  3. namespace Platformer.Core
  4. {
  5.     public static partial class Simulation
  6.     {
  7.         /// <summary>
  8.         /// An event is something that happens at a point in time in a simulation.
  9.         /// The Precondition method is used to check if the event should be executed,
  10.         /// as conditions may have changed in the simulation since the event was
  11.         /// originally scheduled.
  12.         /// </summary>
  13.         /// <typeparam name="Event"></typeparam>
  14.         public abstract class Event : System.IComparable<Event>
  15.         {
  16.             internal float tick;
  17.  
  18.             public int CompareTo(Event other)
  19.             {
  20.                 return tick.CompareTo(other.tick);
  21.             }
  22.  
  23.             public abstract void Execute();
  24.  
  25.             public virtual bool Precondition() => true;
  26.  
  27.             internal virtual void ExecuteEvent()
  28.             {
  29.                 if (Precondition())
  30.                     Execute();
  31.             }
  32.  
  33.             /// <summary>
  34.             /// This method is generally used to set references to null when required.
  35.             /// It is automatically called by the Simulation when an event has completed.
  36.             /// </summary>
  37.             internal virtual void Cleanup()
  38.             {
  39.  
  40.             }
  41.         }
  42.  
  43.         /// <summary>
  44.         /// Event<T> adds the ability to hook into the OnExecute callback
  45.         /// whenever the event is executed. Use this class to allow functionality
  46.         /// to be plugged into your application with minimal or zero configuration.
  47.         /// </summary>
  48.         /// <typeparam name="T"></typeparam>
  49.         public abstract class Event<T> : Event where T : Event<T>
  50.         {
  51.             public static System.Action<T> OnExecute;
  52.  
  53.             internal override void ExecuteEvent()
  54.             {
  55.                 if (Precondition())
  56.                 {
  57.                     Execute();
  58.                     OnExecute?.Invoke((T)this);
  59.                 }
  60.             }
  61.         }
  62.     }
  63. }
RAW Paste Data