Untitled

mail@pastecode.io avatar
unknown
csharp
a month ago
2.4 kB
4
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using System;

public class Statemachine : MonoBehaviour
{
    public NavMeshAgent Agent => GetComponent<NavMeshAgent>();
    [SerializeField] private Animator animator;

    Dictionary<string, BaseState> stateDictionary = new Dictionary<string, BaseState>();
    private BaseState currentState;

    private void Awake()
    {
        stateDictionary.Add("Idle", new Idle(this));
    }

        private void Start()
    {
        currentState = GetInitialState("");

        if (currentState != null)
        {
            currentState.Enter();
        }
    }

    private void Update()
    {
        if (currentState != null)
        {
            currentState.Update();
        }
    }


    public void ChangeState(String stateName)
    {
        if (currentState != null)
        {
            currentState.Exit();
        }

        currentState = stateDictionary[stateName];
        currentState.Enter();
    }

    protected virtual BaseState GetInitialState(String stateName)
    {
        BaseState newState;
        newState = stateDictionary[stateName];

        return newState;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class BaseState
{
    public string name;
    protected Statemachine stateMachine;

    public BaseState(string name, Statemachine stateMachine)
    {
        this.name = name;
        this.stateMachine = stateMachine;
    }

    public virtual void Enter()
    {

    }

    public virtual void Update()
    {

    }

    public virtual void Exit()
    {

    }
}

///////////////////////////////////////////////////////////////

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Idle : BaseState
{
    public Idle(Statemachine stateMachine) : base("Idle", stateMachine) { }

    public override void Enter()
    {
        base.Enter();
    }

    public override void Update()
    {
        base.Update();
    }

    public override void Exit()
    {
        base.Exit();
    }
}

Leave a Comment