0

I created the following three scripts to test out the State pattern in Unity3D (I'm SUPER new to Unity) and got unexpected results:

BaseState

public class BaseState {
    public void Enter()
    {
        Debug.Log("Entered BaseState");
    }
}

IntroState

public class IntroState : BaseState {
    public void Enter()
    {
        Debug.Log("Entered IntroState");
    }
}

StateController

public class StateController : MonoBehavior {
    private BaseState state;

    void Start()
    {
        state = new IntroState();
        state.Enter();
    }
}

When I attach this to a GameObject, I expect to see "Entered IntroState" in the console. Instead, I see "Entered BaseState".

What am I doing wrong?

stevendesu
  • 15,753
  • 22
  • 105
  • 182

1 Answers1

1

You are "hiding" a method when you define it with the same signature in a subclass. You should mark BaseState.Enter as public void virtual and add override in IntroState.Enter so it becomes public override void Enter()

What is happening is that you have a state variable with a BaseState type. When you write state = new IntroState(); you are doing implicit upcasting (google it up). After that you are calling an Enter method on a BaseState object, thats why you get "Entered BaseState"

I also recommend you checking out a library called "Stateless" and this answer for more information

Overriding vs method hiding

netaholic
  • 1,345
  • 10
  • 22