2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Unity AnimationController:トリガー遷移: 数秒ごとにアニメーションを1回実行する

Last updated at Posted at 2023-03-16

実現したいこと

にわとりが5秒毎に卵を生みます。
その際にジャンプするアニメーションが実行されます。

tower2.59.gif

開発環境

IDE:Rider
Unity:2021.3.91
OS:Windows10

実装

animationの設定

animationはアセットに既にあるので、それを利用します。

animatorの設定

animatorの設定をする

図のようにステートマシンを繋げます。
最初はwalkを実行し、walk→jumpとjump→walkと遷移するようにします。
パラメータはTrigger型を1つ加えます。

image.png

walk→jumpの設定

image.png

walk→jumpの矢印部分のインスペクターを開きます。
終了時間ありを非活性にすることでwalkアニメーションがループ実行されます。
ConditionにTriggerを加えます。トリガーが発火するまでwalkアニメーションを実行します。トリガー発火後はjumpアニメーションに遷移します。

jump→walkの設定

jump→walkの矢印部分のインスペクターを開きます。
1回実行したらwalkに遷移するよう 終了時間ありを活性にします。
ConditionにTriggerは追加しません。
jumpアニメーションを実行した後,walkに戻ります。

image.png

動作確認

手動でtriggerを発火して動作確認します。(以下gif参照)
tower2.56.gif

スクリプトの実装

コード部分

5秒おきにアニメーションを実行するようにスクリプトを作成します。

chicken.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chicken : MonoBehaviour
{
    private bool isMakeEgg=true;
    // UIの更新で使う
    public static Action OnMakeEgg;
    private Animator _animator;
    void Start()
    {
        _animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isMakeEgg == true)
        {
            isMakeEgg = false;
            StartCoroutine(IEMakeEgg(5));
        }
    }

    private IEnumerator IEMakeEgg(float makeTime)
    {
+        _animator.SetTrigger("trigger");
        yield return new WaitForSeconds(makeTime);
        Debug.Log("卵を生みました。");
        isMakeEgg = true;
        OnMakeEgg?.Invoke();
    }
    
}

動作確認

作成したスクリプトをAnimatorと同じオブジェクトにアタッチします。
tower2.59.gif

期待した動きを確認できます。

参考

素材はアセットストアより

設定の仕方がとても役立った 

公式ドキュメント

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?