Generic State Class

Instead of creating another CharacterState class and inheriting EnemyState and PlayerState from it. You could just create a generic class and share the functionality of the “State” class.

using Godot;
using System;

public abstract partial class State<T> : Node where T : CharacterBody3D
{
    protected T characterNode;

    public override void _Ready()
    {
        characterNode = GetOwner<T>();
    }

    public override void _Notification(int what)
    {
        base._Notification(what);

        switch (what)
        {
            case StateMachine.Notifications.EnableState:
                EnterState();
                break;
        }
    }

    protected abstract void EnterState();

}

Since the characterNode is going to be of type CharacterBody3D, we can tell the compiler that type T will be of CharacterBody3D and therefore have a single State class.

From our player states we can then do the following:

using Godot;

public partial class PlayerMoveState : State<Player>
{

Maybe this approach has it’s own downsides since you have to remember what generic type to pass to each state.

1 Like

Nice tips, Thanks for sharing. There are always more than one way to do things in coding but sometimes we choose a process to not confuse the learning process to much.
This is a valid way to do things :slight_smile:

Privacy & Terms