How to return a function in C#?

Hi, I’m trying to build an ability system, where I come up with a structure that in my main script component, I have a function called “DoSkill()”, and I have would have variable to store an enum SkillType “currentSkill”.

The SkillType is an enum I defined in another script component called “SkillManager”, My SkillManager have a function called FindSkill(SkillType currentSkill).

So I’m gonna call FindSkill(SkillType currentSkill) in my main script component’s DoSkill(), and then in SkillManager’s FindSkill(SkillType currentSkill), this would do a switch statement to find the correct skill function I pre-defined in SkillManager to return. And then in my main script component, I can use the function returned by FindSkill(SkillType currentSkill)

For example: I defined “Vector3 Dash(float currentTime)” in SkillManager, and I defined enum SkillType {Dash}. In my main script component, I want to

SkillType currentSkill = SkillManager.SkillType.Dash;
float currentTime = 0.5f;
DoSkill() {
   var theRightFunction = FindSkill(currentSkill);  // Where theRightFunction should be Dash(float currentTime)

   // And then I can do like this
   Vector3 answer = theRightFunction(currentTime);
}

I wonder if I’m able to do this. And how should I write my FindSkill. Thanks

You can do this with delegates.

Here is a super bare bones example of passing a function around using the C# default Action void delegate:

public enum SkillTypes
{
    SpecialSkill,
}

private Dictionary<SkillTypes, Action> actions;

// function to be passed around
private void SpecialSkill()
{
    Debug.Log("SpecialSkill Used");
}

// example of assigning it into a dictionary
private void AddSkill()
{
    actions.Add(SkillTypes.SpecialSkill, SpecialSkill); // add the function to the dictionary
}

// looking it up and returning it
private Action FindSkill(SkillTypes type)
{
    return actions[type];
}

// using it
private void DoSkill(SkillTypes type)
{
    Action theSkill = FindSkill(type);
    theSkill();
}
1 Like

You should use code tags to make your post a tad more readable. That said, you can use a lambda expression to achieve this. As well as what has been noted above with delegates. It depends on the complexity of your code.

1 Like