首页 > 解决方案 > 如何在不使用动画师的情况下获得实际的动画播放位置?

问题描述

 anim = GetComponent<Animation>();
 float length = anim.clip.length;
 Debug.Log(length);

将显示以下结果:

 45

如果达到这个位置,动画应该重新开始。任何想法,如何使用 C# 脚本来实现这一点?我没有使用任何动画师,只是 ChildObject 中的动画。当然,这是行不通的,因为它总是正确的:

if(length==45)
anim.Restart();

标签: c#unity3dscripting

解决方案


看起来您希望在动画结束时触发重新启动。所以在动画的最后插入一个 AnimationEvent 。查看 Unity 的简单脚本 API 示例。忽略他们正在使用 Animator 的事实,他们只是使用它来获取剪辑。显然,你已经有了你的剪辑。

https://docs.unity3d.com/ScriptReference/AnimationEvent.html

这是上面链接中修改后的 Unity 脚本。

public void Start()
{
    // existing components on the GameObject
    AnimationClip clip;

    // new event created
    AnimationEvent evt;
    evt = new AnimationEvent();

    // put some parameters on the AnimationEvent
    //  - call the function called PrintEvent()
    //  - the animation on this object lasts 2 seconds
    //    and the new animation created here is
    //    set up to happen 1.3s into the animation
    evt.intParameter = 12345;
    evt.time = 1.3f;
    evt.functionName = "PrintEvent";

    clip.AddEvent(evt);
}

// the function to be called as an event
public void PrintEvent(int i)
{
    print("PrintEvent: " + i + " called at: " + Time.time);
}

推荐阅读