求教,这个自定义的C#类是如何工作的?
程序代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 动画行为类,提供有关动画的行为 /// </summary> public class AnimationAction { //附加在敌人上的动画组件引用 private Animation anim; /// <summary> /// 创建动画行为类 /// </summary> /// <param name="anim"></param> public AnimationAction(Animation anim) { this.anim = anim; } /// <summary> /// 播放动画 /// </summary> /// <param name="animName"></param> public void Play(string animName) { anim.CrossFade(animName); //......... } /// <summary> /// 判断指定动画是否在播放 /// </summary> /// <param name="animName"></param> /// <returns></returns> public bool IsPlaying(string animName) { return anim.IsPlaying(animName); } }这是一个用于Unity 3d 获取动画组件的辅助类,视频里讲,把模型挂在空物体下,脚本挂在空物体上,用一个脚本,获取模型上的动画,而这个类是用于辅助的,但我搞不懂它是怎么起作用的。
1,首先 AnimationAction()这个在做什么?
首先它应该是个构造函数(没有get,没有返回值),他需要被一个对象调用(点它),但是它在做什么?
this.anim = anim 是获取了一个Animation类型的引用,存储到自身的字段?
2,之后的 Play()用字段存储的对象,调用继承的CrossFade()方法,来播放动画
所以这个方法为的是省去每次书写么?
视频中的使用方法:
EnemyAnimation anim;
anim.action.Play(anim.runAnimName);
附action的定义入
程序代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 敌人动画,定义需要播放的动画片段名称 /// </summary> public class EnemyAnimation : MonoBehaviour { public string runAnimName; public string attackAnimName; /// <summary> /// 闲置 /// </summary> public string idleAnimName; public string deathAnimName; public AnimationAction action; private void Awake() { action = new AnimationAction(GetComponentInChildren<Animation>()); } }
附2:对上面进行调用的脚本
程序代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 敌人AI /// </summary> [RequireComponent(typeof(EnemyAnimation))] [RequireComponent(typeof(EnemyMotor))] [RequireComponent(typeof(EnemyStatusInfo))] public class EnemyAI : MonoBehaviour { //定义敌人状态 public enum State { //攻击 Attack , //寻路 PathFinding } /// <summary> /// 敌人当前状态 /// </summary> private State currentState = State.PathFinding; private EnemyAnimation anim; private EnemyMotor motor; private void Start() { anim = GetComponent<EnemyAnimation>(); motor = GetComponent<EnemyMotor>(); } private float atkTimer; /// <summary> /// 攻击间隔 /// </summary> public float atkInterval = 3; private void Update() { //判断 switch (currentState) { case State.PathFinding: PathFinding(); break; case State.Attack: Attack(); break; } //寻路,攻击 } private void PathFinding() { anim.action.Play(anim.runAnimName); //执行寻路 调用motor类中寻路方法,播放跑步动画 //如果寻路结束,修改状态为攻击 if (motor.Pathfinding() == false) currentState = State.Attack; } private void Attack() { if (anim.action.IsPlaying(anim.attackAnimName) == false) anim.action.Play(anim.idleAnimName); //如果动画没有播放 if (atkTimer <= Time.time) { //进行攻击 播放攻击动画 anim.action.Play(anim.attackAnimName); atkTimer = Time.time + atkInterval; } } }
[此贴子已经被作者于2019-7-22 22:03编辑过]