unityでanimationを使うと,永遠に繰り返すか,一度だけ実行されるか,,
と思っていたのですが
簡単に実装できてしまったので,紹介します.
実装環境
- Unity.2019.3.3f.1
実装方法
1.animationの作成
Animationタブを加える.

HierarchyからGameObjectを選択すると,先ほど作成したタブにCreateボタンが出てくるのでそれをクリック.
適当な名前で保存すると,AnimationとAnimatorControllerが出現
適当にAnimationを作り,
inspecterからLoopにチェックを入れる(大事)

2.AnimatorをつけたGameObjectにスクリプトをつける
まず,Animatorからスクリプトを再生するのは
public class camera_earthquake : MonoBehaviour
{
    Animator earthQ;//適当な名前で良い
    // Start is called before the first frame update
    void Start()
    {
        earthQ = this.gameObject.GetComponent<Animator>();//animatorを取得
        earthQ.Play("earthquake");//Animationの名前を入れてplay
    }
}Code language: HTML, XML (xml)今回は10回繰り返したらやめることとする.
「GetCurrentAnimatorStateInfo(0).normalizedTime」これがanimationを繰り返した回数を示す.
つまり,半分まで実行されると,0.5
一回実行されると1,5回実行されると5
便利.
ちなみに「AnimatorStateInfo(0)」の数字はレイヤー番号を示す.
基本的には0で大丈夫だと思うが,アニメーションレイヤーについてはリファレンスを参照
https://docs.unity3d.com/ja/2018.4/Manual/AnimationLayers.html
アニメーションレイヤー
作成したコードはこんな感じ
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera_earthquake : MonoBehaviour
{
	Animator earthQ;
    // Start is called before the first frame update
    void Start()
    {
        earthQ = this.gameObject.GetComponent<Animator>();
        earthQ.Play("earthquake");
    }
    // Update is called once per frame
    void Update()
    {
    	if(earthQ.GetCurrentAnimatorStateInfo(0).normalizedTime > 10)
    	{
    		//10回繰り返したら
    		//enabledで停止
    		earthQ.enabled = false;
    	}
    }
}
Code language: HTML, XML (xml)3.終わりに
これで上下に動かす地震のアニメーションを作成しました.
地震の作り方もメモしておかないとなぁ

コメント