- Home /
How do you store a function in a variable in c#?
I want to be able to store a function in a variable, so that later i can call it from that variable?
Answer by Razor1994 · May 21, 2020 at 10:05 PM
Hey,
this question has already been answered (check the link below), let me know if the article helped you or if you need further help :)
https://answers.unity.com/questions/925943/storing-a-method-in-a-variable.html
Answer by unity_ek98vnTRplGj8Q · May 21, 2020 at 10:14 PM
Use and Action if the function does not return a value and a Func if it does
https://stackoverflow.com/questions/7367152/dynamically-assign-method-method-as-variable
private Func<int, int, out int> myFunction;
int Add(int a, int b){
return a + b;
}
int Subtract(int a, int b){
return a - b;
}
void DoStuff(){
int a = 10;
int b = 5;
myFunction = Add;
Debug.Log(myFunction());
myFunction = Subtract;
Debug.Log(myFunction());
}
Your answer
Follow this Question
Related Questions
Graph/function in editor 1 Answer
Range of Unitys Variables 2 Answers
Object B doesn't see Variable values that Object A does 1 Answer
How Can I Disable a function if a variable equals zero 1 Answer
Linking Variable Values 1 Answer