unity使用代码在动画片段中添加event

unity使用代码在动画片段中添加event

csharp 复制代码
using UnityEngine;

public static class AnimationHelper
{
    /// <summary>
    /// 获取Animator状态对应的动画片段
    /// </summary>
    /// <param name="animator">Animator组件</param>
    /// <param name="stateName">状态名(动画片段名)</param>
    /// <returns>对应状态的AnimationClip</returns>
    public static AnimationClip GetClipFromAnimator(Animator animator, string stateName)
    {
        if (animator == null)
        {
            Debug.LogError("Animator is null!");
            return null;
        }

        // 获取 Animator 的 Controller
        var animatorController = animator.runtimeAnimatorController;

        if (animatorController == null)
        {
            Debug.LogError("Animator Controller is null!");
            return null;
        }

        // 获取所有动画片段
        foreach (var clip in animatorController.animationClips)
        {
            if (clip.name == stateName)
            {
                return clip;
            }
        }

        Debug.Log($"没有找到名为 {stateName} 的动画片段!");
        return null;
    }

    /// <summary>
    /// 向指定的动画剪辑添加事件
    /// </summary>
    /// <param name="clip">要添加事件的动画剪辑</param>
    /// <param name="time">事件触发的时间点(单位:秒)</param>
    /// <param name="functionName">事件触发时调用的函数名称</param>
    /// <param name="useFrames">是否使用帧数来设置事件时间(如果为 true,则 `time` 参数会被解释为帧数)</param>
    public static void AddEventToClip(AnimationClip clip, float time, string functionName, bool useFrames = false)
    {
        if (clip == null)
        {
            Debug.LogError("AnimationClip is null!");
            return;
        }

        // 获取动画的帧率
        float fps = clip.frameRate > 0 ? clip.frameRate : 60f; // 默认 60fps

        if (useFrames)
        {
            // 如果使用帧数,将帧数转换为时间(秒)
            time = time / fps; // 将帧数转换为秒数
        }

        // 如果时间小于0,则将其修正为0(动画开始时间)
        if (time < 0f)
        {
            time = 0f;
        }

        // 如果时间超过动画长度,则将其修正为动画的结束时间
        if (time > clip.length)
        {
            time = clip.length;
        }

        // 创建一个新的动画事件实例
        AnimationEvent animationEvent = new AnimationEvent
        {
            // 设置事件的触发时间
            time = time,

            // 设置事件触发时调用的函数名称
            functionName = functionName
        };

        // 将事件添加到动画剪辑中
        clip.AddEvent(animationEvent);
    }

    /// <summary>
    /// 清空动画剪辑中的所有事件
    /// </summary>
    /// <param name="clip">目标动画剪辑</param>
    public static void ClearAllEventsFromClip(AnimationClip clip)
    {
        if (clip == null)
        {
            Debug.LogError("ClearAllEventsFromClip: AnimationClip is null!");
            return;
        }

        clip.events = new AnimationEvent[0];
        Debug.Log($"ClearAllEventsFromClip: All events cleared from clip '{clip.name}'.");
    }

    /// <summary>
    /// 删除动画剪辑中指定函数名称的事件
    /// </summary>
    /// <param name="clip">目标动画剪辑</param>
    /// <param name="functionName">要删除的事件函数名称</param>
    public static void RemoveEventFromClip(AnimationClip clip, string functionName)
    {
        if (clip == null)
        {
            Debug.LogError("RemoveEventFromClip: AnimationClip is null!");
            return;
        }

        if (string.IsNullOrEmpty(functionName))
        {
            Debug.LogError("RemoveEventFromClip: Function name is null or empty!");
            return;
        }

        // 获取当前所有事件
        AnimationEvent[] events = clip.events;

        // 过滤掉指定的事件
        var filteredEvents = new System.Collections.Generic.List<AnimationEvent>();
        foreach (var evt in events)
        {
            if (evt.functionName != functionName)
            {
                filteredEvents.Add(evt);
            }
        }

        // 将过滤后的事件重新赋值给动画片段
        clip.events = filteredEvents.ToArray();
    }

}

示例代码

将这个脚本挂到带有动画的物体上,然后动画的片段叫做:DoRotate

然就会在动画的第10帧,停止动画,等待3秒之后再次执行动画且不会被打断。

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjAni : MonoBehaviour
{


    private Animator animator;

    private void Start()
    {
        animator = gameObject.GetComponent<Animator>();

        var clip = AnimationHelper.GetClipFromAnimator(animator, "DoRotate");

        AnimationHelper.AddEventToClip(clip, 30, nameof(AnimatorEventAdd), true);

        animator.SetBool("work", true);
        Invoke(nameof(RemoveEventClip), 3.0f);

    }



    private void AnimatorEventAdd()
    {
        animator.SetBool("work", false);
        Debug.Log("AnimatorEventAdd");
    }

    void RemoveEventClip()
    {
        var clip = AnimationHelper.GetClipFromAnimator(animator, "DoRotate");
        AnimationHelper.RemoveEventFromClip(clip, nameof(AnimatorEventAdd));
        animator.SetBool("work", true);
    }

}
相关推荐
黄思搏1 天前
Unity坐标转换指南 - 3D与屏幕UI坐标互转
ui·3d·unity
weixin_424294671 天前
在 Unity 游戏开发中,为视频选择 VP8 还是 H.264
unity·游戏引擎
一步一个foot-print2 天前
【Unity】Light Probe 替代点光源给环境动态物体加光照
unity·游戏引擎
@LYZY2 天前
Unity 中隐藏文件规则
unity·游戏引擎·游戏程序·vr
霜绛2 天前
C#知识补充(二)——命名空间、泛型、委托和事件
开发语言·学习·unity·c#
Sator12 天前
使用Unity ASE插件设置数值不会生效的问题
unity·游戏引擎
程序猿追2 天前
轻量级云原生体验:在OpenEuler 25.09上快速部署单节点K3s
人工智能·科技·机器学习·unity·游戏引擎
B0URNE2 天前
【Unity基础详解】(7)Unity核心:动画系统
unity·游戏引擎
我的golang之路果然有问题2 天前
mac M系列芯片 unity 安装会遇到的错误以及解决
经验分享·学习·macos·unity·游戏引擎
Hody913 天前
【XR开发系列】2025 年 XR 开发入门,我该选择 Unity 还是 Unreal Engine?
unity·xr·虚幻