Remove all clips from animation by script

Hello,

How to remove all AnimationClips from Animation via script? The same as set Size in editor to 0 but from script. I'm trying do do so:

while ( animation.GetClipCount() > 0 )
    for (var state : AnimationState in animation) 
        if ( state )
        {
            animation.RemoveClip( state.clip );
            break;
        }

but the Unity crashes if there is a clip marked in editor as "None". Can't find out why is it so.

Is it another way? Or I'm doing something wrong?

Indeed, while it is online. People will find it. Also there is not much about threads in Unity, specially if you look for recent (and updated) posts.

2 Answers

2

How about this: (AnimationWipeArray.cs):

using UnityEngine;
//using System.Collections;

public class AnimationWipeArray : MonoBehaviour {

    void Start () {
        //for demonstration purposes, wipe out our animation as if we had changed the array size to 0 in the Inspector
        EmptyAnimationStateArray(gameObject);
    }

    void EmptyAnimationStateArray(GameObject go) {  
        if (!go.animation) return;

        WrapMode savedWrapMode = animation.wrapMode;
        bool savedPlayAutomaticallyState = go.animation.playAutomatically; 
        bool savedAnimatePhysicsState = go.animation.animatePhysics;
#if UNITY_3_0
        bool savedAnimateOnlyIfVisibleState = go.animation.animateOnlyIfVisible;
#endif

        //destroy the old
        DestroyImmediate(go.GetComponent(typeof(Animation)));
        //create the new
        Animation newAnim = (Animation)go.AddComponent(typeof(Animation));
        newAnim.wrapMode = savedWrapMode;
        newAnim.playAutomatically = savedPlayAutomaticallyState;
        newAnim.animatePhysics = savedAnimatePhysicsState;
#if UNITY_3_0
        newAnim.animateOnlyIfVisible = savedAnimateOnlyIfVisibleState;
#endif
    }

}

oops, I made a typo in line 14, should be: WrapMode savedWrapMode = go.animation.wrapMode;

This fits as an alternative solution. Thank you :)

"None" usually indicates null object, IIRC, so maybe doing "if (state && state.clip)" would help?

Thank you for the comment. No, it's the same.