#finite state machine

1 messages · Page 1 of 1 (latest)

sand venture
#

Code but would be nice to have a list or an array in the inspector to add or remove states for each enemy

What i have now

.
├── BaseAIController.controller
├── EnemyBaseState.cs
├── Enemy.cs
└── StateScripts
    ├── EnemyAttackState.cs
    ├── EnemyReturnToOriginState.cs
    ├── EnemyRunToPlayerState.cs
    └── EnemyWanderState.cs
median sapphire
#

Is this the gameobject/component hierarchy?

sand venture
#

This is in my Scripts/Enemy folder

median sapphire
#

With pure code and states set up like this, the simplest solution is to create a specific enemy controller for each enemy type and have it manage adding the states to the FSM in an initialize call, which is something I've done before.

sand venture
#

Do you have an example on how thats done ?

median sapphire
#

Not off hand. Before I give a high level example, the are classes in StateScripts monobehaviours/scriptable objects or standard C# classes?

sand venture
#

EnemyRunToPlayerState

using UnityEngine;

public class EnemyRunToPlayerState : EnemyBaseState
{
    public override void OnCollisionEnter(Enemy enemy, Collider2D collider)
    {
        // throw new System.NotImplementedException();
    }

    public override void OnDrawGizmosSelected(Enemy e)
    {
        // throw new System.NotImplementedException();
    }

    public override void UpdateState(Enemy enemy)
    {
        GameObject detectedObject;

        Debug.Log("Detected objs" + enemy.detectedObjs.Count);
        if (enemy.detectedObjs.Count == 0){
            Debug.Log("go to wander");
            enemy.SwitchState(enemy.wanderState);
            return;
        }

        detectedObject = enemy.detectedObjs[0].gameObject;

        if (detectedObject == null || enemy.detectedObjs.Count == 0)
        {
            enemy.SwitchState(enemy.wanderState);
        }
        else if (detectedObject != null || enemy.detectedObjs.Count > 0)
        {

            enemy.transform.position = Vector2.MoveTowards(enemy.transform.position, detectedObject.transform.position, enemy.enemyAsset.speed * Time.deltaTime);
            float distance = Vector2.Distance(enemy.transform.position, detectedObject.transform.position);

            if (distance < enemy.enemyAsset.meleeRadius)
            {
                enemy.SwitchState(enemy.enemyAttackState);
            }
        }
    }
}
median sapphire
#

From the overrides I assume that it is a monobehaviour?

sand venture
#

The EnemyBaseState is an abstract class and the Enemy class has MonoBehaviour

median sapphire
#

In that case you could create a SpecificEnemyOneController monobehaviour and in Awake or wherever you like running initialization code, use GetComponents<EnemyBaseState> to collect all the state components attached to the same game object

#

Then put those instances into the FSM