Most efficient approach for state machine

Hi, I am trying to optimize my scripts for best performance on mobile devices. I am needing some advice on objects that need state control scripts (e.g. Enemies). I am trying to figure out what would be the best approach in terms of script optimization when it comes to handling enemy or player states .

Each time an enemy changes a state (e.g. search, shoot, die), it affects the object’s NavMeshAgent and AnimationController. I have tried the following:

  1. Do everything in Update() based on current state. I eventually added a timer since it seems like a bad idea to change animation and navmesh properties every frame.

  2. I handle switching between states with Invoke calls (usually with a 0.5f delay)

The next thing I will try is to handle states with Coroutines.

I am interested to hear how other people are scripting their state machines and AI. I am not experiencing massive performance issues, but would like to try and avoid unnecessary strain on the cpu, which in turn might allow me to do more with my Enemy scripts.

Thanks

Here’s everyone’s favorite answer: “It depends.” In a mobile game, it might be sufficient to disable all offscreen enemies. Then they’re not using any CPU in Update, Invoke, or a coroutine.

If they still need to update while offscreen, I like to use a coroutine that scales its update cycle according to distance from the player. Roughly something like this:

private float updateFrequency = 1;

IEnumerator Start() {
    InvokeRepeating("ScaleFrequencyByDistance", 0, 5);
    while (true) {
        UpdateStateMachine(); //<-- Your code in here.
        yield return new WaitForSeconds(updateFrequency);
    }
}

private void ScaleFrequencyByDistance() {
    updateFrequency = Vector3.Distance(this.transform.position, player.transform.position);
}

(I did say roughly. You could optimize little things and make some values configurable, but the code above is purposely simple for clarify.)

So every 5 seconds the enemy checks how far it is from the player, which determines how frequently it “thinks”.

You might also be able to make a lot of things event driven. For example, only update the NavMeshAgent when the enemy registers a collision or trigger, and only spawn a projectile when the enemy’s fire animation sends an animation event. This way you’re not constantly polling state.

1 Like

Those are good suggestions, updating only when necessary is key. Evaluating the conditions for necessity is cheaper than actually executing.

I used an int to specify how many update cycles to skip, but this can make your AI feel laggy. Code snippet below.

private IEnumerator StateMachine()
        {
            int i = IgnoreUpdates;
            while (true)
            {
                while (ThisSubject.IsDead) { yield return null; }
                DoLocomotion();
                while (i > 0)
                {
                    i--;
                    yield return null;
                }

                i = IgnoreUpdates;

                yield return StartCoroutine(ProcessConditions()); // looks at context, sets the most appropriate mood for MyMood.

                switch (MyMood)
                {
                    case (Mood.Idle):
                        StartCoroutine(Idle());
                        break;
                    case (Mood.Patrol):
                        StartCoroutine(Patrol());
                        break;
                    case (Mood.Wander):
                        StartCoroutine(Wander());
                        break;
<...snip snip...>
                }
            }
        }

I’ve implemented the distance check idea before as well and it does make a massive improvement.

1 Like

Thanks guys, very helpful. It seems coroutines are great for this. And I guess there is lots you can do with objects that are offscreen like disable animations and so on.

Appreciate it :slight_smile: