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);
    }

}
相关推荐
大模型铲屎官3 小时前
Unity C# 与 Shader 交互入门:脚本动态控制材质与视觉效果 (含 MaterialPropertyBlock 详解)(Day 38)
c语言·unity·c#·交互·游戏开发·材质·shader
暴走约伯7 小时前
【虚幻5蓝图Editor Utility Widget:创建高效模型材质自动匹配和资产管理工具,从3DMax到Unreal和Unity引擎_系列第二篇】
unity·ue5·游戏引擎·虚幻·材质
一颗橘子宣布成为星球15 小时前
Unity AI-使用Ollama本地大语言模型运行框架运行本地Deepseek等模型实现聊天对话(一)
人工智能·unity·语言模型·游戏引擎
一个程序员(●—●)19 小时前
漫反射实现+逐像素漫反射+逐像素漫反射实现
unity·着色器
weixin_423995001 天前
unity 读取csv
unity·c#
EQ-雪梨蛋花汤1 天前
【Flutter】Flutter + Unity 插件结构与通信接口封装
flutter·unity·游戏引擎
折纸星空Unity课堂1 天前
Unity之基于MVC的UI框架-含案例
ui·unity·mvc
暴走约伯1 天前
【3DMax脚本MaxScript开发:创建高效模型虚拟体绑定和材质管理系统,从3DMax到Unreal和Unity引擎_系列第一篇】
3d·unity·材质·unreal·maxscript
SlowFeather2 天前
Unity 使用 ADB 实时查看手机运行性能
android·unity·adb·性能优化·profiler
小赖同学啊2 天前
Unity 和 Unreal Engine(UE) 两大主流游戏引擎的核心使用方法
unity·游戏引擎·虚幻