Can I have a method as a parameter ?
Hi,
I wanted to create a method whics executes a method on a keypress. Something like this:
public void OnKeyPress(KeyCode kc, Method stuffToExecute){
if(Input.GetKeyDown(kc){
stuffToExecute();
}
What should replace Method stuffToExecute ?
Or is it possible somehow ?
Delegates are clunky and a little obsolete. As Elarm writes, System.Func/Action is a nicer way, but also clunky (they both do the same thing, but you have to use one of the other depending on the function.)
The whole idea is known as Function Pointers. It's a common language feature, and works exactly as your example. You can even do more, like store a function in a variable. $$anonymous$$y favorite explanation is in the Function Pointer chapter at taxesforcatses (but it's like 15 pages.)
Cool site, bookmarked, thx! (Couldn't find the author's info.)
Answer by GamerJoHo · Jun 19, 2017 at 08:45 AM
Hi,
If you pass in a string, you can Invoke the method.
Such as:
public void OnKeyPress(KeyCode kc, string stuffToExecute){
if(Input.GetKeyDown(kc){
Invoke("stuffToExecute", 0.01f)
}
I write 0.01f to invoke it then, as i'm not sure 0f will be accepted. Your turn to play with that one!
Answer by Elarm00 · Jun 19, 2017 at 12:34 PM
Yup!
You can use System.Action, ex.
//---------------------------------------------------------
public void OnKeyPressed(KeyCode keyCode, System.Action func)
{
if (Input.GetKeyDown(keyCode))
func();
}
You can even pass parameters, ex.
//---------------------------------------------------------
public void OnKeyPressed(KeyCode keyCode, System.Action<KeyCode> func)
{
if (Input.GetKeyDown(keyCode))
func(keyCode);
}
Also check out System.Func and delegates.