Created
October 29, 2019 14:04
-
-
Save verborghs/392fb3876e250ee70adcb6c2f303bde3 to your computer and use it in GitHub Desktop.
TimedQueue using delegates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.UI; | |
namespace Utils | |
{ | |
public class ShowMessages : MonoBehaviour | |
{ | |
[SerializeField] | |
private Text _message; | |
private TimedQueue queue; | |
void Start() | |
{ | |
queue = new TimedQueue(ShowMessage, ShowDefaultMessage); | |
queue.Enqueue("one"); | |
queue.Enqueue("Ha Ha"); | |
queue.Enqueue("two"); | |
queue.Enqueue("Ha Ha"); | |
} | |
public void ShowMessage(string t) | |
{ | |
_message.text = t; | |
} | |
public void ShowDefaultMessage() | |
{ | |
_message.text = "default message"; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.UI; | |
namespace Utils | |
{ | |
public class TimedQueue | |
{ | |
private float _dequeueTimer; | |
private readonly float _dequeueDelay; | |
private float _emptyTimer; | |
private readonly float _emptyDelay; | |
private readonly Queue<string> _messageQueue = new Queue<string>(); | |
public delegate void OnMessage(string t); | |
private OnMessage _callbackMessage; | |
public delegate void OnEmpty(); | |
private OnEmpty _callbackEmpty; | |
public TimedQueue(OnMessage callbackMessage, OnEmpty callbackEmpty, float dequeueDelay = 0.5f, float emptyDelay = 2.0f) | |
{ | |
_callbackMessage = callbackMessage; | |
_callbackEmpty = callbackEmpty; | |
_dequeueDelay = dequeueDelay; | |
_dequeueTimer = dequeueDelay + 0.1f; | |
_emptyDelay = emptyDelay; | |
_emptyTimer = _emptyDelay + 0.1f; | |
} | |
public void Update(float deltaTime) | |
{ | |
if (_messageQueue.Count > 0) | |
{ | |
_emptyTimer = 0; | |
if (_dequeueTimer > _dequeueDelay) | |
{ | |
_callbackMessage(_messageQueue.Dequeue()); | |
_dequeueTimer = 0; | |
} | |
_dequeueTimer += deltaTime; | |
} | |
else | |
{ | |
if (_emptyTimer < _emptyDelay) | |
{ | |
_emptyTimer += deltaTime; | |
if (_emptyTimer > _emptyDelay) | |
{ | |
_callbackEmpty(); | |
} | |
} | |
} | |
} | |
public void Enqueue(string t) | |
{ | |
_messageQueue.Enqueue(t); | |
_emptyTimer = 0.0f; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment