Menu Close

ExtendedMonoBehaviour.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExtendedMonoBehaviour : MonoBehaviour
{
    #region Standard Methods
    private void Update()
    {
        CallCustomUpdates();
    }

    #endregion

    #region Update Methods running at special Intervals

    private float _lastUpdate1 = -1f;
    private float _lastUpdate2 = -1f;
    private float _lastUpdate4 = -1f;
    private float _lastUpdate5 = -1f;
    private float _lastUpdate10 = -1f;

    private float GetDeltaTime(float lastCalled)
    {
        if (lastCalled < 0f) return 0f;

        return (Time.time - lastCalled);
    }
    private void CallCustomUpdates()
    {
        UpdateEachFrame();

        if (Time.time > _lastUpdate1 + 1f)
        {
            Update1xPerSecond(GetDeltaTime(_lastUpdate1));
            _lastUpdate1 = Time.time;
        }

        if (Time.time > _lastUpdate2 + 0.5f)
        {
            Update2xPerSecond(GetDeltaTime(_lastUpdate2));
            _lastUpdate2 = Time.time;
        }

        if (Time.time > _lastUpdate4 + 0.25f)
        {
            Update4xPerSecond(GetDeltaTime(_lastUpdate4));
            _lastUpdate4 = Time.time;
        }

        if (Time.time > _lastUpdate5 + 0.2f)
        {
            Update5xPerSecond(GetDeltaTime(_lastUpdate5));
            _lastUpdate5 = Time.time;
        }

        if (Time.time > _lastUpdate10 + 0.1f)
        {
            Update10xPerSecond(GetDeltaTime(_lastUpdate10));
            _lastUpdate10 = Time.time;
        }
    }

    public virtual void UpdateEachFrame()
    { 
    }
    public virtual void Update1xPerSecond(float deltaTime)
    { 
    }
    public virtual void Update2xPerSecond(float deltaTime)
    { 
    }
    public virtual void Update4xPerSecond(float deltaTime)
    {
    }
    public virtual void Update5xPerSecond(float deltaTime)
    {
    }
    public virtual void Update10xPerSecond(float deltaTime)
    { 
    }

    #endregion
}