0

I know in javascript, I can pass in a function name, and an array of vars, and then execute that function with those vars at an arbitrary moment in time later.

It makes it easier that everything is basically the same var thing. In C#, there is also var, but it looks like the type gets defined depending on what you place into it.

What I am trying to accomplish is to say:

take the function and parameters: foo(bar1,bar2...barN)

and execute them in 5 seconds.

I'm using Unity, so the timing part is simple, but I can't figure out how to pass a function and specify arbitrary possible parameters of arbitrary types.

pseudo code:

class myTimerClass{
   functionHandle myFunction;
   var params;
   float startTime, delayTime;
   bool pending = false;

   public myTimerClass(functionHandle myFunction, var params, float delay){
     this.myFunction = myFunction;
     this.params = params;
     this.delay = delay;
     this.startTime = System.currentTime;
     pending = true;
   }
   public void update(){
     if(System.currentTime>=startTime+delay && pending){
         pending = false;
         INVOKE(myFunction,params);
     }
   }

}
<something calls the update() every frame>

I've read up on action and func<> and delegates, but there doesn't seem to be a way to handle an arbitrary function with arbitrary params.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Roman Rekhler
  • 475
  • 6
  • 6
  • Possible duplicate of [C# delayed function calls](http://stackoverflow.com/questions/545533/c-sharp-delayed-function-calls) – Thomas Weller Aug 06 '16 at 15:57
  • Just use the most general function type, `Delegate`, and then its `Invoke` method. – Wiktor Zychla Aug 06 '16 at 15:57
  • Look at the third answer, not the accepted one. You don't need `bar()`, you can do it all in the lambda. IMHO it's quite similar to JavaScript, where setTimeout() also uses a timer. – Thomas Weller Aug 06 '16 at 15:59
  • Thomas, I couldn't get your suggestion to work, as I didn't have the available library in unity. (at least by default). But this worked perfectly: http://answers.unity3d.com/answers/932529/view.html – Roman Rekhler Aug 06 '16 at 16:46

1 Answers1

1

After more searching, I finally found what works:

http://answers.unity3d.com/answers/932529/view.html

I can pass literally any code and it will execute at any time. Perfect!

Now I have a separate class (just to keep it neat) that has the following block:

public void doThingAfterTime(System.Action action, float time){
    StartCoroutine(CoroutineUtils.DelaySeconds(action,time));
}

So I can do something like

doThingAfterTime (() => doPrint ("s", "d"), 2);

that will work find to call that function, that, for reference is:

public void doPrint(string s, string s2){
    print (s);
    print (s2);
}
Roman Rekhler
  • 475
  • 6
  • 6