Animatorで動かしているけどスクリプト上でも動かしたい

Unity
Animatorで動かしているけどスクリプト上でも動かしたい

Unityでクライアントエンジニアの山中です。

SkinnedMeshRendererなどAnimatorで動かしているけどスクリプト上で動かしたい時がありました。
しかし値が変更されません。
当然動かしたい物が入っているアニメーションを設定しているステートとは別ステートの時です。

そこでステートを使用する時にアニメーションクリップを設定して、ステートを使用しない場合は空のアニメーションクリップを設定するようにいたしました。
するとステートを使用しない場合にスクリプト上で動かせるようになりました。
おそらく別ステートの時でも値を固定してるのでしょうね。

下記は作成した処理です。

宣言
・private Animator animator;
・private AnimatorOverrideController animatorOverrideController;

変数
・isPlayはステート仕様のフラグ

Resourcesに
・アニメーションさせるAnimationClipのanim_clip
・新規作成から何も弄っていないAnimationClipのno_anim_clip

Animatorのステートは
・no_anim
・animがtrueの時のanim

        if (isPlay)
        {
            // クリップの更新
            var animationClipList = new List<KeyValuePair<AnimationClip, AnimationClip>>();
            animatorOverrideController.GetOverrides(animationClipList);
            int index = animationClipList.FindIndex(x => x.Key.name == "anim_clip");
            if (index >= 0 && (animationClipList[index].Value == null || animationClipList[index].Value.name != "anim_clip"))
            {
                animationClipList[index] = new KeyValuePair<AnimationClip, AnimationClip>(animationClipList[index].Key, Resources.Load<AnimationClip>("anim_clip"));
                animatorOverrideController.ApplyOverrides(animationClipList);
                // コントローラーの更新
                animator.runtimeAnimatorController = animatorOverrideController;
            }
            // アニメーション変更
            animator.SetBool("anim", true);
        }
        else
        {
            // アニメーション終了
            animator.SetBool("anim", false);
            animator.Play("no_anim", 1, 0);
            // クリップの更新
            var animationClipList = new List<KeyValuePair<AnimationClip, AnimationClip>>();
            animatorOverrideController.GetOverrides(animationClipList);
            int index = animationClipList.FindIndex(x => x.Key.name == "anim_clip");
            if (index >= 0 && (animationClipList[index].Value == null || animationClipList[index].Value.name != "no_anim_clip"))
            {
                animationClipList[index] = new KeyValuePair<AnimationClip, AnimationClip>(animationClipList[index].Key, Resources.Load<AnimationClip>("no_anim_clip"));
                animatorOverrideController.ApplyOverrides(animationClipList);
                // コントローラーの更新
                animator.runtimeAnimatorController = animatorOverrideController;
            }
        }

以上 山中がお伝えしました。またお会いしましょう!

この記事をシェアする