//注意:本文章中将update写成了updata导致其无法正常运行,在参考过程中请务必将其改正
Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : Entity
{
//以下全为受保护的对象
public Rigidbody2D rb { get; private set; }
public Animator anim { get; private set; }
//设置可读属性
public EnemyStateMachine stateMachine { get; private set; }//定义敌人状态机类
//唤醒控制器
protected override void Awake()
{
base.Awake();
stateMachine = new EnemyStateMachine();//创建敌人状态机类
}
//持续更新敌人配置
protected override void Updata()
{
base.Updata();
stateMachine.currentState.Update();
}
}
SkeletonIdleState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SkeletonIdleState : EnemyState
{
EnemySkeleton enemy;
public SkeletonIdleState(Enemy _enemyBase,EnemyStateMachine _stateMacine , string _animBoolName, EnemySkeleton _enemy) : base(_enemyBase,_stateMacine, _animBoolName)
{
enemy = _enemy;
}
public override void Enter()
{
base.Enter();
stateTimer = 1f;
}
public override void Exit()
{
base.Exit();
}
public override void Update()
{
base.Update();
if (stateTimer < 0)
{
stateMachine.ChangeState(enemy.moveState);
}
}
}
SkeletonMoveState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SkeletonMoveState : EnemyState
{
private EnemySkeleton enemy;
public SkeletonMoveState( Enemy _enemyBase,EnemyStateMachine _stateMacine, string _animBoolName, EnemySkeleton _enemy) : base(_enemyBase,_stateMacine, _animBoolName)
{
this.enemy = _enemy;
}
public override void Enter()
{
base.Enter();
}
public override void Exit()
{
base.Exit();
}
public override void Update()
{
base.Update();
enemy.SetVelocity(2 * enemy.facingDir, enemy.rb.velocity.y);
if(enemy.IsWallDetected()||!enemy.IsGroundDetected())
{
enemy.Flip();
stateMachine.ChangeState(enemy.idleState);
}
}
}
EnemySkeleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySkeleton : Enemy
{
#region States
public SkeletonIdleState idleState { get; private set; }
public SkeletonMoveState moveState { get; private set; }
#endregion
protected override void Awake()
{
base.Awake();
idleState = new SkeletonIdleState(this,stateMachine, "Idle",this);
moveState = new SkeletonMoveState(this,stateMachine, "Move",this);
}
protected override void Start()
{
base.Start();
}
protected override void Updata()
{
base.Updata();
}
}
报错信息与解决方案
The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(EnemySkeleton) <rb>k__BackingField
报错,子脚本和 父脚本 具有 相同 名字 和类型 的变量。
错误原因,Enemy继承了Entity时并未将
-
public Rigidbody2D rb { get; private set; }
-
public Animator anim { get; private set; }删除
解决方法:
把子脚本 或者 父脚本 的int 类型 的同名变量test_更改其中的一个 名字,使其 都不重名。