AI and Input Switch C#

Hi, what happen is that I have a Set of Animation Script that is control by a Manager.

Inside a Manager, there is a isAI bool parameter.

When isAI is true, it will relay all Controls from AI Module to AnimationScript.
When isAI is false, every control will be from Player Input.

The problem is,
my current Code goes something like this.


Bool ActionOne()
{
     if(isAI) return ActionOneAI();
     return ActionOnePlayer();
}

Bool ActionOneAI(){ return AIModule.ActionOne(); }
Bool ActionOnePlayer(){ return PlayerInput.ActionOneButton() }

Float ActionTwo()
{
     if(isAI)return ActionTwoAI();
     return ActionTwoPlayer();
}

Float ActionTwoAI(){ return AIModule.ActionTwo(); }
Float ActionTwoPlayer() { return PlayerInput.ActionTwoFloat() }

And So on for each Function,

When Ideally, it should go by something like this


//Automatically call this if isAI == true

Bool ActionOne()
{
     return AIModule.ActionOne();
}

//Automatically call this if isAI == false

Bool ActionOne()
{
     PlayerInput.ActionOneButton();
}

Is there anyway to do this or something similar in C#?

I would do it in the following way…

  1. Create interface IInputProvider with appropriate methods

    public interface IInputProvider
    {
    bool ActionOne();
    float ActionTwo();
    // etc.
    }

  2. Make both AIModule and PlayerInput implement this interface, and provide implementation of the methods. For example, your AIModule should look like:

    public class AIModule : IInputProvider
    // or, if AIModule inherits from MonoBehaviour: public class AIModule : MonoBehaviour, IInputProvider
    {
    #region IInputProvider implementation

     public bool ActionOne()
     {
         // content of your action
     }
    
     public float ActionTwo()
     {
         // content of your action
     }
    
     // etc.
    
     #endregion
    
     // other class content
    

    }

  3. Inside your manager, create a private property CurrentInputProvider with getter only, returning appropriate implementation:

    public AIModule aiModule; // set in inspector if AIModule inherits from MonoBehaviour or change to private and assign in Awake if it’s a standard class
    public PlayerInput playerInput; // same as above

    private IInputProvider CurrentInputProvider
    {
    get { return isAI ? aiModule : playerInput; }
    }

  4. Change your methods in Manager to:

    bool ActionOne()
    {
    return CurrentInputProvider.ActionOne();
    }

    float ActionTwo()
    {
    return CurrentInputProvider.ActionTwo();
    }

The above code snippets are untested, but even if there are some errors, the general idea remains.