目的:精确控制动画某一帧发生的事件,常用来校对同步效果。
-
实现方式一:在动画面板插入事件
image.png
这个脚本的object选项必须选带实现这个事件方法的脚本来接收。
public class GooseAnimationEvent : MonoBehaviour
{
Animationer animationer;
private void Start()
{
animationer = this.GetComponent<Animationer>();
}
public void AnimationEventStartSpark(string msg)
{
Debug.Log("收到动画事件");
//do something
}
}
以上两种方法Object赋值的都是你的脚本。
注意:这个事件脚本必须挂在这个物体带有Animator的物体上(其他物体不行)。否则会出现如下错误:
'NoviceKnight' AnimationEvent 'Skode_ActiveIdleLoop' has no receiver! Are you missing a component?
有时候如果你在使用别人的动画时莫名其妙报这个错误,就要去看看引入的动画是不是带了动画事件。
- 实现方式二:全部在代码里添加
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeTest : MonoBehaviour
{
Animation _anim;
public GameObject target;
private AnimationClip clip;
void Start()
{
_anim = GetComponent<Animation>();
clip = _anim.GetClip("cube2");
AddAnimationEvent();
if (_anim != null)
{
_anim.Play("cube2");
}
}
/// <summary>
/// 代码中自定义事件
/// </summary>
public void AddAnimationEvent()
{
//创建动画事件
AnimationEvent animationEvent = new AnimationEvent();
//设置事件回掉函数名字
animationEvent.functionName = "CallFuncation";
//传入参数
animationEvent.objectReferenceParameter = target;
//设置触发帧
animationEvent.time = 1f;
//注册事件
clip.AddEvent(animationEvent);
}
/// <summary>
/// 动画帧事件
/// </summary>
public void CallFuncation()
{
Debug.Log("Animation Event Triggered !");
}
}
![](https://img.haomeiwen.com/i13721461/023403869fe450a4.gif)
-
实现方式三:针对在Unity里自带的动画编辑器制作的动画,也可以在这样添加
image.png
对应修改的代码:
public class CubeTest : MonoBehaviour
{
Animation _anim;
public GameObject target;
private AnimationClip clip;
void Start()
{
_anim = GetComponent<Animation>();
clip = _anim.GetClip("cube1");
//clip = _anim.GetClip("cube2");
AddAnimationEvent();
if (_anim != null)
{
_anim.Play("cube1");
//_anim.Play("cube2");
}
}
/// <summary>
/// 代码中自定义事件
/// </summary>
public void AddAnimationEvent()
{
//创建动画事件
AnimationEvent animationEvent = new AnimationEvent();
//设置事件回掉函数名字
animationEvent.functionName = "CallFuncation";
//传入参数
animationEvent.objectReferenceParameter = target;
//设置触发帧
animationEvent.time = 1f;
//注册事件
clip.AddEvent(animationEvent);
}
/// <summary>
/// 动画帧事件
/// </summary>
public void CallFuncation()
{
Debug.Log("Animation Event Triggered !");
}
public void CallFunctionCube1()
{
Debug.Log("这是动画cube1");
}
}
其他问题:
有可能会遇到的问题,动画使用时报动画事件没有接收者的错误,那是因为在导入别人的动画时,动画本身带了事件,去掉即可解决。
网友评论