- Home /
C# | How to delay a method with parameters
I got a line of code that is basicly a component from inside this main component, calling a method from that component while passing a parameter from this component. Here:
posCard place = DropZone.GetComponent<posCard>();
place.AddCardEnemy (card);
Now, how to delay this line, if Invoke only takes methods without params and Coroutine needs an IEnum?
Answer by jdean300 · Jul 19, 2016 at 04:02 AM
Create a new coroutine method that waits a given amount of time and then calls the method:
public IEnumerator AddCardEnemyDelayed(float t, posCard place, Card card)
{
yield return new WaitForSeconds(t);
place.AddCardEnemy(card);
}
//This can then be called by:
StartCoroutine(AddCardEnemyDelayed(1f, place, card));
Answer by Nodata · Jun 24, 2020 at 04:59 PM
This class will allow you to extend any monobehaviour and run delayed coroutines with parameters:
public static class MonoBehaviourExt
{
public static IEnumerator DelayedCoroutine(this MonoBehaviour mb, float delay, System.Action a)
{
yield return new WaitForSeconds(delay);
a();
}
public static Coroutine RunDelayed(this MonoBehaviour mb, float delay, System.Action a)
{
return mb.StartCoroutine(mb.DelayedCoroutine(delay, a));
}
//Example
//public class Buff: MonoBehaviour
//{
// public void OnBuff()
// {
// StopAllCoroutines();
// Debug.Log("buffed");
// this.RunDelayed(2f,() => {
// Debug.Log("Debuffed");
// });
// }
//}
}
You may want to have a look at my CoroutineHelper. It provides several static methods which allow to schedule delegates at different times / conditions. It starts the coroutines on a seperate monobehaviour singleton.