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?

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

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.