0

I'm using Unity3D and trying to achieve the following. I want to store in the class some parameters as well as "special rules" - which ment to be the functions in this or other class.

Ideally I would want something that behaves like this:

public class Weapon
{
    public DamageHandler damageHandler; //script that have all special rule functions
    public string weaponName;
    public int damage;
    public ???? specialRule; //this is the rule of interest

    public void DealDamage()
    {
        damageHandler = GetComponent<DamageHandler>();
        damageHandler.specialRule(damage); //call the function that is set in Weapon Class
    }        
}

I know that I can save specialRule as a string and use reflection. Is there any other way/better way to handle such situation?

Alex
  • 189
  • 1
  • 1
  • 10

1 Answers1

4

What you are looking for is a Action<int> my friend.

public class Weapon
{
    public DamageHandler damageHandler; //script that have all special rule functions
    public string weaponName;
    public int damage;
    public Action<int> specialRule; //this is the rule of interest

    public void DealDamage()
    {
        damageHandler = GetComponent<DamageHandler>();
        damageHandler.specialRule(damage); //I call the function with the name that is set in Weapon Class
    }        
}

Action<ParamType1, ParamType2, ParamType3, .....> represents a void function delegate.

Func<ParamType1, ParamType2, ParamType3, ....., ReturnType> represents a function with a return value

each one can take anywhere from 1 or 2 type parameters, to i believe about 17 or so

maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37