Perhaps a bit of an odd question, but a while ago I read on here about the Low level player loop system with which you can use to add your own update loops.
So in my efforts to decouple the core of my project’s time system from any other system, I went about implementing my own loops to give me global callbacks for when the game ‘ticks’ every 1 second. The issue is, once I leave play mode, the loop keeps getting called.
Here’s the code so far, with editor code to prevent the ticking outside of play mode:
namespace TheFault.Core.Time
{
using System;
using UnityEngine;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
using LizardBrainGames.LowLevel;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class TheFaultGameTimeLoop
{
#region Initialisation
[RuntimeInitializeOnLoadMethod]
private static void InitialiseGameTimeLoop()
{
PlayerLoopSystem currentPlayerLoop = PlayerLoop.GetDefaultPlayerLoop();
PlayerLoopSystem gameTimeTickLoop = new PlayerLoopSystem()
{
updateDelegate = GameTimeTickLoop,
type = typeof(GameTimeTickType)
};
UnityEnginePlayerLoopUtilities.AddPlayerLoopToSubSystem<Update>(ref currentPlayerLoop, gameTimeTickLoop);
PlayerLoop.SetPlayerLoop(currentPlayerLoop);
Application.quitting += () =>
{
OnGameTimeTick = null;
};
}
#endregion
#region Update Struct Types
public struct GameTimeTickType { }
#endregion
#region Internal Properties
private static bool CanTickGameTime
{
get
{
#if UNITY_EDITOR
if (EditorApplication.isPlaying == false) return false;
if (EditorApplication.isPaused == true) return false;
#endif
return true;
}
}
#endregion
#region Game Time Global Delegates
public static event Action OnGameTimeTick;
#endregion
#region Game Time Loop
private static void GameTimeTickLoop()
{
if (CanTickGameTime == false) return;
Debug.Log("Game Time Tick!");
//Call 'OnGameTimeTick' every 1 second
}
#endregion
}
}
UnityEnginePlayerLoopUtilities
is my own class with helper methods to add in my own player loop subsystem, as it’s a bit of an epic to do so.
Ideally I’d prefer if the loops just stopped once I left play mode and not require any editor code. I’ve tried copying over the loopConditionFunction from some of the other existing loops, such as Update, to no avail.
Would anyone here who’s also used this system have any insight in how to do so?
The alternative of course is to just use a monobehaviour with static delegates, but here I was hoping to make a non-monobehaviour alternative.