10
9

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 5 years have passed since last update.

[Unity] iTweenで動作完了を待つ

Posted at

iTweenでアニメーションをしていてハマったのでメモ。

iTweenは2度呼び出しても、2度アニメーションするとは限らない

	public void OnGUI(){
		if(GUI.Button(new Rect(0, 0, 100, 50), "Push"){
			iTween.MoveAdd(target, new Vector3(0, 50, 0), 0.1f);
		}
	}

上記のようなスクリプトがあるとする。
GUI上のボタンが押されたら、targetオブジェクトがy軸上を50上に移動するというものである。

このスクリプトを実行して、ボタンを2度押したとしても、100移動するとは限らない(移動する場合もある)。

ようは、2度目にボタンを押したタイミングで、1度目のiTweenの処理が終わっていればもう一度実行されるが、終わっていない場合は1度目の処理がキャンセルされて2度目の処理だけしてしまうようだ(推測)。

特に問題のないケースも多いだろうが、何度押されたかによって処理がかわる場合などには好ましくない。

1度目の処理中は、2度目の呼び出しを無視する

そこで、iTweenの処理が終わってからしか、次の入力を受け付けないようにしてみた。

	// 処理が終わったどうかを示すフラグ
	bool iTweenMoving = false;
	// 処理が終わったら呼び出され、フラグをクリアする。
	void OnCompleteHandler(){
		iTweenMoving = false;
	}

	public void OnGUI(){
		if( ! iTweenMoving && GUI.Button(new Rect(0, 0, 100, 50), "Push"){
			// 処理中のフラグをたてとく。
			iTweenMoving = true;
			iTween.MoveAdd(target, iTween.Hash(
				"y", 50,
				"time", 0.1f,
				"oncomplete", "OnCompleteHandler",
				"oncompletetarget", this.gameObject));
		}
	}

iTweenが処理中はフラグをたてといて、終わったらコールバック関数を呼び出してもらい、そこでフラグをクリアしているだけである。

10
9
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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?