- Home /
Function as parameter?
Is this possible? Would it look something like this?
public void Hey() {}
public static void Hat(k) { /*What type is the function?*/
Hey = k;
}
public static void Run() {
Hey();
}
//How would I call this?
$$anonymous$$aybe you can google for "lambda expressions" and "delegates". That's a starting point.
I think i did something with generics too, this might help you
http://stackoverflow.com/questions/16184014/how-to-use-classes-themselves-as-method-parameters
other than that most people would use lambda expression and Delegates like Andres said
I have tried something with delegates, but I could assign Hey to be k with it?
Answer by Glurth · Jan 09, 2015 at 09:22 AM
I like using Action, nice and simple. (you can use Action < T >
instead, for functions with a parameter)
static class ActionTest
{
public static Action Hey;
public static void Hello(){Debug.Log ("Hello");}
public static void Hola(){Debug.Log ("Hola");}
public static void Hat(Action k) {
Hey = k;
}
public static void Run() {
Hat (Hello);
Hey();
Hat (Hola);
Hey();
}
}
It says that Action isn't a valid type (error CS0246)
EDIT: Nvm I just had "using System.Collections" ins$$anonymous$$d of "using System". But now I have 2 new errors:
public static Action OnYes() {} //error CS0161: `Game.OnYes()': not all code paths return a value.
public static void Popup( string text, Action onYes) {
instance.ShowPopup = true;
instance.PopupText = text;
OnYes = onYes; //error CS0131: The left-hand side of an assignment must be a variable, a property or an indexer
}
public static Action OnYes() {}
this declares a method returning an Action type object, I think you want to create a delegate of type Action:
public static Action OnYes = ()=>{};
Perhaps you meant somthing like this?
public static void OnYesFunction() {}
public static Action OnYesAction;
public static void Popup( string text, Action onYes) {
instance.ShowPopup = true;
instance.PopupText = text;
OnYesAction= onYes;
}
now we call Popup like this:
Popup("blah",OnYesFunction);
Note, the action is not actually executed in the code above. To actually run the function in Popup, rather than store it for later, just replace
OnYesAction= onYes;
with
onYes();
Your answer
Follow this Question
Related Questions
Passing a Script Name to a Function 2 Answers
iTween - calling functions on oncomplete doesn't work if the function is declared as a variable 1 Answer
How to correctly send a variable to another function? 1 Answer
Calling non applied scripts 3 Answers
Cleaning up my item script... Passing script name to function? 0 Answers