Documentation
Features
πŸ“ž Unity Callback

πŸ“ž UnityCallbackService

The UnityCallbackService allows any other service (or any other piece of code anywhere in the project) to subscribe to the default MonoBehaviour callbacks.
Sometimes code just needs to execute once on a LateUpdate for example, this service allows such behavior without the need of needing a GameObject and a component.

Default Unity callbacks

The available callbacks for code to subscribe:

  • Update
  • LateUpdate
  • FixedUpdate
  • StartCoroutine
  • StopCoroutine
  • ApplicationPause
  • ApplicationFocus
  • ApplicationQuit
⚠️

Quit in editor
Application.Quit() is called in the editor but not on mobile device, add your requires functionality when the app is paused or focus is lost.

Camera render events

  • OnPreRender
  • OnPostRender
⚠️

Main camera tag
It subscribes these to the Camera.main, if it can find it. So aim to only have the in-game camera set to use the MainCamera tag, the rest of the cameras should have None or some other tag set.

Invoking

  • IEnumerator Invoke(Action callback, float delay)
  • CancelInvoke(IEnumerator enumerator)

Use Invoke() to implement a delayed execution of a method.

If the reference becomes invalid over time, please unsubscribe from the delayed call by passing in the IEnumerator that was returned when creating the delayed call.

// Call MyMethod after 1.5 seconds. Save the enumerator to be able to cancel it later.
IEnumerator enumerator = unityCallbackService.Invoke(MyMethod, 1.5f);
 
// Cancel the invoke by passing in the enumerator.
unityCallbackService.CancelInvoke(enumerator);

Thread safe

InvokeOnMainThread(Action callback)

Use this method when having multithreaded code running and you need to execute on the main thread or use Unity specific actions that are not supported on another thread.

Thread safe
If this code is being called while already on the main thread, it will execute immediately. If it is not called on the main thread, it will be called next Unity Update cycle, in the order it was called.

Unsubscribing

Always store a copy of the UnityCallbackService, check if it is null and unsubscribe when destroying the asset. Like in the example below:

using GameSuite;
 
namespace Game
{
	public class ExampleService : IDisposable
	{
		private UnityCallbackService unityCallbackService;
		
		public ExampleService(UnityCallbackService unityCallbackService)
		{
			this.unityCallbackService = unityCallbackService;
			unityCallbackService.Update += Update;
		}
		
		private void Update()
		{
			// Implement logic here that executes every Unity Update.
		}
		
		public void Dispose()
		{
			if (unityCallbackService != null)
			{
				unityCallbackService.Update -= Update;
			}
		}
	}
	
	public class ExampleServiceFactory : IServiceFactory<ExampleService>
	{
		public int Order => 0;
		
		public ExampleService Create()
		{
			return new ExampleService(
				Services.Get<UnityCallbackService>());
		}
	}
}