Return to Snippet

Revision: 72377
at August 19, 2017 00:24 by halfchuckieboy


Updated Code
public delegate void TimerCallbacks();
public static event TimerCallbacks EverySecond;

void Start ()
	{
		StartCoroutine(Timer(1f, EverySecond, true));
	}

public IEnumerator Timer (float timeDelay, TimerCallbacks methodToCall, bool loop = false)
	{
		if (loop)
		{
			yield return new WaitForSeconds (timeDelay);

			if (methodToCall != null)
			{
				methodToCall ();
			}

			yield return StartCoroutine (Timer(timeDelay, methodToCall, true));
		}
		else
		{
			yield return new WaitForSeconds (timeDelay);

			if (methodToCall != null)
			{
				methodToCall ();
			}

			yield return null;
		}
	}

Revision: 72376
at August 10, 2017 21:45 by halfchuckieboy


Initial Code
public delegate void TimerCallbacks();
public static event TimerCallbacks EverySecond;

void Start ()
	{
		StartCoroutine(Timer(1f, EverySecond, true));
	}

IEnumerator Timer (float timeDelay, TimerCallbacks methodToCall, bool loop = false)
	{
		if (loop)
		{
			yield return new WaitForSeconds (timeDelay);

			if (methodToCall != null)
			{
				methodToCall ();
			}

			yield return StartCoroutine (Timer(timeDelay, methodToCall, true));
		}
		else
		{
			yield return new WaitForSeconds (timeDelay);

			if (methodToCall != null)
			{
				methodToCall ();
			}

			yield return null;
		}
	}

Initial URL

                                

Initial Description
A timer that activates a delegate after a set amount of time. Coded for Unity. This example shows the implementation of an event where all subscribed methods are activated every second. For methods with more elaborate signatures, new delegates will have to be added.

The public IEnumerator can be started from external classes using "StartCoroutine()" and can be passed methods from that class matching the TimerCallbacks delegate signature.

Initial Title
Delegate Activation Timer (Example)

Initial Tags

                                

Initial Language
C#