Search code examples
c#unity-game-enginetimerdelegatescoroutine

Timer for functions with any parameters


I'm working with unity, but in this instance it's just a c# question. Is there a way to make a timer that will run any function, with any parameters? I've been using delegates to put a function into either a timer class or coroutine, but I can't figure out how to put any parameters into the delegate.

Also, there are many questions like mine, but the difference (since I couldn't find any addressing specifically what I'm asking) is that I want to be able to run a function, any function I want, no matter what parameters it may or may not need, after a specified amount of seconds have passed. Essentially I want to be able to run a coroutine that takes float time and a delegate function. It waits for time seconds, and then runs the delegate function. But then, I need to be able to put in parameters for the function if it needs it, so if I want to run a simple function that does

Debug.Log(comment)

after taking comment as a string parameter, or

Debug.Log(number)

after taking number as a float parameter.

So to sum up, how can I wait for x seconds to perform function y, and change what y is to whatever I want without having to create a new set of delegates and functions?

I apologize if this is a duplicate question, or easily accessible information, as I've been unable to find anything answering it after about an hour of searching.


Solution

  • It seems to be impossible to have as flexible a solution I wanted, but I got around it by creating a set of zero/one/two/etc. parameter delegates and coroutines, so if I want to wait 5 seconds to run a function called debugHello and put "hello" as a parameter for debugHello, I would put debugHello into a delegate instance of oneParamMeth called debugHelloMeth and then do StartCoroutine(oneParamMethTimer(5, debugHellometh, "hello")); . This way, at least with void functions, I can do as many parameters as I like as long as I make a new pair of delegate and coroutine to go with them.

    EDIT: DerHugo's comment works much better! A lot cleaner than mine.