- Home /
Storing a method in a variable
Hey All,
I am trying to store a method as a variable, but I don't know how. I have a weapon script that I am using to set all of my munition types, damages, ranges, etc. I used enums to list some of the basic weapon styles, such as missile, assault rifle, sniper rifle,etc. What I want to do is call one firing method for the rifles and a different firing method for the missile functions. I planned on storing the the method in a "var" according to a switch for the enum, but I get errors when I do that ( Error CS0815: Cannot assign void to an implicitly-typed local variable (CS0815)) how can I switch the method for firing depending on what my weaponType enum is?
Answer by raulrsd · Mar 17, 2015 at 01:16 AM
You need to use delegates.
First declare the Delegate and a variable to store the method:
public delegate void FiringDelegate();
FiringDelegate firingMethod;
Then you need to implement the method. As our delegate has been declared without parameters, the method can't have parameters either.
void FiringSniper(){
//DO WHATEVER
}
Finally you could store the method in the variable and execute it this way:
firingMethod = FiringSniper;
firingMethod();
You can even pass the method as a parameter:
//declare the method
void ExecuteFiring(FiringDelegate miMethod){
miMethod();
}
//call the method
ExecuteFiring(FiringSniper);
Hope it helps
This worked great!! thank you for your help. Just out of curiosity, I tried it with a IEnumerator and it didn't work. Is there a way to call a startCoroutine method this way?
You're welcome. I've never tried it with StartCoroutine but I've found this piece of code in unity forums:
public class TestIng : $$anonymous$$onoBehaviour {
public delegate IEnumerator WaitFunction(int f);
void Start ()
{
WaitFunction func = Wait;
StartCoroutine(func(2));
}
IEnumerator Wait(int f)
{
yield return new WaitForSeconds(1f);
Debug.Log(f + " " + Time.time);
}
}
http://forum.unity3d.com/threads/delegates-and-co-routines-and-yield-waitforseconds.49221/
Answer by Cherno · Mar 17, 2015 at 01:09 AM
You could store the name as a string and then use the SendMessage function to call that function along with up to one other parameter.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why the variable don't change your value? 1 Answer
Accessing variable from a method in another script and gameObject 2 Answers