DarkRewar / BaseTool

A big library of basic tools that you might need in your Unity projects.
MIT License
41 stars 6 forks source link

TickManager #43 #67

Closed DarkRewar closed 5 months ago

DarkRewar commented 5 months ago

TickManager

The TickManager component allows you to create a system that sends a tick every x seconds. You can define the delay between two ticks by modifying the Tick Duration field. You can also make the TickManager a singleton by checking Make Singleton (it will convert it to a singleton at Awake, don't do that at runtime!).

To add the component, you can go to Add Component > BaseTool > Core > Tick Manager. You can have more than one TickManager on a singleton GameObject, but it is highly recommended to use only one TickManager (as singleton) or seperate them between multiple GameObjects.

image

You can subscribe to the tick event from the inspector (using UnityEvent) or the OnTick event action.

using BaseTool;
using UnityEngine;

public class TickerTest : MonoBehaviour
{
    [SerializeField] private TickManager _tickManager;

    void Start()
    {
        _tickManager.OnTick += OnTick;
    }

    private void OnTick() => Debug.Log("OnTick()");
}

If you want to add more custom tick, you can create a struct that implements the ICustomTick interface, and create you own tick logic. The interface implements the ShouldTick(ulong tick) method where tick is the current number of ticks elapsed since the beginning of the game.

The following example shows how to create a custom tick that process every two ticks only:

using BaseTool;
using UnityEngine;

public struct EveryTwoTicks : ICustomTick
{
    public bool ShouldTick(ulong tick) => tick % 2 == 0;
}

public class TickerTest : MonoBehaviour
{
    [SerializeField] private TickManager _tickManager;

    private void OnEnable()
    {
        _tickManager.RegisterCustomTick<EveryTwoTicks>(OnEveryTwoTicks);
    }

    private void OnDisable()
    {
        _tickManager.UnregisterCustomTick<EveryTwoTicks>(OnEveryTwoTicks);
    }

    private void EveryTwoTicks() => Debug.Log("EveryTwoTicks()");
}