Advice on best state machine

Hi Guys,

I’m trying to make a template for a projectile weapon. I’m thinking I’ll use a state machine as an abstract template for all weapon classes, and run from that. Where I’m confused is whether it’s better to have a ‘FireWeapon’ coroutine, which has a switch statement handling whatever is the current firing state and running through them sequentially. Being handled by a bProcessingFire, which says whether to continue. Or whether it’s worth having a delegate array of coroutines where each one handles a different process of the firing state. The reason I may think that may be useful is if any external features want to end or override a state or state sequence, or add methods to each state dynamically. They’ll be able to override the actions midway and make their own (e.g someone halfway through shooting gets hit with a weapon, forcing them to recoil and their prefiring animation overridden).

using UnityEngine;
using System.Collections;

namespace CDSFramework
{
    public abstract class WeaponFramework : BaseFramework
    {
        // The firing sequence
        enum WeaponState { Ready, PreFire, Fire, PostFire, Reload, Count }
        private delegate IEnumerator WeaponFireDelegate();
        private WeaponFireDelegate[] weaponFireStates;
        private bool bPendingFire = false;
        private bool bProcessingFire = false;

        protected override bool Initialise()
        {
            return base.Initialise();
        }

        public virtual void RequestFire()
        {
            bPendingFire = true;
            StartCoroutine(BeginFire());
        }

        protected virtual IEnumerator BeginFire()
        {
            yield return null;
        }

    }
}

The only issue is with a delegate array is that I’ll need something to control when it’s activated and ended. I was thinking of just having a delegate array run through the Update function, but that meant it’ll ALWAYS be checking some boolean, and won’t be able to use any yield timed events. So instead I’m thinking it might be an idea to start ANOTHER coroutine called BeginFire(), which runs through calling the delegate array coroutines through their states… ?

What’s your thoughts guys? I know both will ‘work’, but I want to improve myself.

Thanks! :smile:

top right, thread tools, edit title

1 Like