Alex教程每一P的教程原代码加上我自己的理解初步理解写的注释,可供学习Alex教程的人参考
此代码仅为较上一P有所改变的代码
【Unity教程】从0编程制作类银河恶魔城游戏_哔哩哔哩_bilibili
Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
#region 组件
public Animator anim { get; private set; }
public Rigidbody2D rb { get; private set; }
#endregion
#region 类
public EnemyStateMachine stateMachine;
public EnemyIdleState idleState;
#endregion
private void Awake()
{
stateMachine = new EnemyStateMachine();
idleState = new EnemyIdleState(this, stateMachine, "Idle");
anim = GetComponentInChildren<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
stateMachine.Initialize(idleState);
}
void Update()
{
stateMachine.currentState.Update();
}
}
EnemyState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyState
{
protected Enemy enemy;
protected EnemyStateMachine stateMachine;
protected bool triggerCalled;
private string animBoolName;
protected float stateTimer;
public EnemyState(Enemy _enemy, EnemyStateMachine _stateMachine, string _animBoolName)
{
this.enemy = _enemy;
this.stateMachine = _stateMachine;
this.animBoolName = _animBoolName;
}
public virtual void Enter()
{
triggerCalled = false;
Debug.Log("I enter" + animBoolName);
enemy.anim.SetBool(animBoolName, true);
}
public virtual void Update()
{
stateTimer -= Time.deltaTime;
Debug.Log("I'm in " + animBoolName);
}
public virtual void Exit()
{
enemy.anim.SetBool(animBoolName, false);
}
}
EnemyStateMachine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyStateMachine
{
public EnemyState currentState { get; private set; }//记得加private set,不然很可能会被外部改了
public void Initialize(EnemyState _startState)
{
currentState = _startState;
currentState.Enter();
}
public void ChangeState(EnemyState _newState)
{
currentState.Exit();
currentState = _newState;
currentState.Enter();
}
}
EnemyIdleState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyIdleState : EnemyState
{
public EnemyIdleState(Enemy _enemy, EnemyStateMachine _stateMachine, string _animBoolName) : base(_enemy, _stateMachine, _animBoolName)
{
}
public override void Enter()
{
base.Enter();
}
public override void Exit()
{
base.Exit();
}
public override void Update()
{
base.Update();
}
}