Passing Func event as parametar

Hi this is more a C# question but might be useful to people using unity.
I am writing the countdown script that is going to be used like this:

//simple countdown duration:10s, when done call OnFinish
this.gameObject.AddComponent<Countdown>().StartCountdown(10,OnFinished);
//overloaded, countdown duration:10s when done call OnFinish, report in 1s call OnProgress
this.gameObject.AddComponent<Countdown>().StartCountdown(10,OnFinished,1,OnProgress);

countdown script is attached to the GO that needs countdown and destroys itself when done. I managed to use simple Action event for OnFinish and OnProgress but i could not get the Func to work since i want to return some values to the script that uses the countdown.

here is the current countdown script, help me expand this and learn along the way! thanks!

using UnityEngine;
using System;
using System.Collections;

public class Countdown : MonoBehaviour {

	float startTime;
	float elapsedTime;
	
	event Action Finished;
	event Action Progress;
	int progressCount;
	
	public void StartCountdown(int seconds, Action OnFinished)
	{
		Finished += OnFinished;
		StartCoroutine(Count(seconds));
	}
	
	public void StartCountdown(int seconds, Action OnFinished, int progress, Action OnProgress)
	{
		Finished += OnFinished;
		Progress += OnProgress;
		progressCount = (int)(seconds / progress);
		StartCoroutine(CountWithProgress(seconds,progress));
	}
	
	IEnumerator Count(int duration)
	{
		startTime = Time.time;
		
		while(elapsedTime < duration)
		{
			elapsedTime = startTime + Time.time;
			yield return null;
		}
		
		if(Finished != null)
			Finished();
		
		Destroy(this);
	}
	
	IEnumerator CountWithProgress(int duration, int progress)
	{
		int i = 1;
		startTime = Time.time;
		
		while(elapsedTime < duration)
		{
			elapsedTime = startTime + Time.time;
			
			if(elapsedTime > progress * i)
			{
				if(Progress != null)
					Progress();
				
				i++;
			}
			
			yield return null;
		}
		
		if(Finished != null)
			Finished();
		
		Destroy(this);
	}
}

Just use a generic Func<> delegate instead of an Action. When you look at the left side of the MSDN page you will see there are a lot different Func and Action delegates. Those are to specify the parameters and the return type of your delegate.

Btw, i would expect the OnProgress delegate to get the current countdown value as parameter.

ps. your elapsedTime calculation is wrong :wink: It should be:

elapsedTime = Time.time - startTime ;

See this Stackoverflow question for more information about Action and Func delegates :wink: