Function as argument
Is it possible to pass a function as an argument ? I've tried searching for this but I find things that are not related to what I'm looking for.
I've got a coroutine used to fill a progression bar. As long as the player hold the action key, the process carry on. When the progress bar is full, the coroutine trigger a function.
It look like this :
IEnumerator ProgressBar(RaycastHit hit)
{
int actionProgress = 1;
while((Input.GetButton("Action"))){
yield return new WaitForSeconds(0.03f);
actionProgress++;
if(actionProgress >= 100) doSomething(hit);
yield return null;
}
}
Now I want to use this coroutine for multiple action, opening a door, planting a bomb or whatever. Is it possible to call my function like this :
StartCoroutine(ProgressBar(hit, some-function);
IEnumerator ProgressBar(RaycastHit hit, Function func)
{
int actionProgress = 1;
while((Input.GetButton("Action"))){
yield return new WaitForSeconds(0.03f);
actionProgress++;
if(actionProgress >= 100) func(hit);
yield return null;
}
}
Answer by vladrybak · Sep 28, 2015 at 03:08 PM
You can use System.Action to do that.
void DoSomething(RaycastHit hit){
Debug.Log("Doing something");
}
IEnumerator ProgressBar(RaycastHit hit, System.Action<RaycastHit> func){
func(hit);
yield break;
}
void Start(){
RaycastHit hit = new RaycastHit();
System.Action<RaycastHit> func = DoSomething;
StartCoroutine(ProgressBar(hit, func));
}
And if you want more complicated behaviour, learn about delegates.
Your answer
Follow this Question
Related Questions
StopCoroutine not working. 0 Answers
Queue a Coroutine with a List? 1 Answer
C# coroutine not waiting on waitForSeconds? 2 Answers
Stop previous coroutine and start new one from beginning 1 Answer