別オブジェクトのアニメーション実行を待機させる方法

2020/09/17
カテゴリー: Unity


Unityでアニメーションを実行中に他ゲームオブジェクトのアニメーションを 待機させる方法です。

ゲームオブジェクトを用意

テストとしてボタンを押したらアニメーションするゲームオブジェクトを二つ用意します。
今回は、UIのImageを二つくりImage1、Image2とします。そしてアニメーション再生用タンを二つ作ります。


Animator作成

続いて、Animationを用意し、Animatorを作ります。
Parametersから再生用のTriggerと待機させるようのBoolのパラメータを追加、
何もしないIdleステータスとWaitステータス、そして用意したAnimationを追加します。
これをImage1用とImage2用2つ作りコンポーネントで追加します。

ボタンを押すとアニメーションを再生するプログラムを書く


using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestScript : MonoBehaviour { GameObject image1, image2; private void Start() { image1 = GameObject.Find("Image1"); image2 = GameObject.Find("Image2"); } public void OnClickButton1() { image1.GetComponent().SetTrigger("playAnimation1"); } public void OnClickButton2() { image2.GetComponent().SetTrigger("playAnimation2"); } }

実行してみる


当然、ステータスWaitには行きませんね。
これを片方がアニメーションしてる間は、もう片方は待機させるようにします。

本編

まずはスクリプトをステートマシンのアニメーションから追加します。
中身をこのようにします。

using System.Collections; using System.Collections.Generic; using UnityEngine; public class DoWait : StateMachineBehaviour { Animator anotherAnimator; override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //アニメーション始まった時 if (animator.name.Equals("Image1")) anotherAnimator = GameObject.Find("Image2").GetComponent(); else anotherAnimator = GameObject.Find("Image1").GetComponent(); anotherAnimator.SetBool("wait", true); } override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //アニメーション終わった時 anotherAnimator.SetBool("wait", false); } }
そしてじっこうしてみると。。。
しっかりともう片方のボタンを押したときにWaitステートに行ってくれましたね。
実行結果も相手のアニメーションをしっかりと待っているようになりました。