State machine - How to pass information on what to do on success to state

Viewed 61

I am using my own state machine for my AI in my city management game, it works fairly well. I uses a very simple interface:

public interface IState
{
    int Id { get; set; }

    void Enter();
    void Execute();
    void Exit();
}

To change state:

public void ChangeState(IState newState)
    {

        if (currentState != null)
            currentState.Exit();

        if (currentState != newState)
        {
            currentState = newState;
            currentState.Enter();
        }
    }

My only issue with it is that I find my self re-writing a lot of logic, to give a scenario:

There are bakers, blacksmiths, construction workers, and more. All these professions have a state that find the closest storage facility and go to it to gather the material they need for their job.

The same logic is used for all of them, apart from the line that says what to do when you get to the storage, i.e a baker will want to get wheat and then return to their bakery. A Blacksmith will want to get some iron and return to their blacksmith.

Basically what they do is:

  1. Find storage
  2. Go to storage
  3. If storage has resource, change state to go back to workplace
  4. Else find next closest storage and see if that storage has the resource
  5. repeat 3 until found resource.

As you can imagine, I have the exact same issue with state "go back to workplace", where its basically the exact same logic in the state, except what to do on arrival.

Is there some smart way I can create a single state called "FindStorageState" and pass it information on what to do when my unit has arrived?

Here is a good example of what a profession can look like:

enter image description here

0 Answers
Related