1
2

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 > TDD > 動作テスト用gameobjectのON/OFFで処理を繰り返す

Last updated at Posted at 2015-09-13
動作確認
Unity 5.1.3-f1 on MacOS X 10.8.5

問題点

http://qiita.com/7of9/items/5835021b3ae22dd09b9f
において、テスト用ゲームオブジェクト(Test_weekly)をActivateした時にテストコードの実行ができた。

ただし、処理の実行を繰り返すことができない。

Start(), Awake()からの関数実行を試したが、できなかった。

forum.unity3d
によると、最後のLysanderさんが以下のように書いている。

The answer is to use the OnDisable() and OnEnable() functions of the component in order to check the status of the GameObject, and then react if the entire thing has been disabled. Next time you should read to the end of the thread first IMO.

テスト用GameObject(Test_weekly)のActived/Deactivatedを監視するGameObjectを用意して、それがTest_weeklyのActivateを検知したら、処理をする、ということらしい。

実装

テスト用GameObject (Test_hello)とスクリプトTest_hello.cs (下記) を用意。
外部GameObjectからコールするため static public宣言としている。

Test_hello.cs
using UnityEngine;
using System.Collections;

public class Test_hello : MonoBehaviour {

	static public void Test_showHelloMessage() {
		Debug.Log ("Hello from Test_hello");
	}
}

テスト用GameObject監視用GameObject (Test_helloGoChecker)とスクリプト Test_helloGoChecker.cs(下記)を用意

Test_helloGoChecker.cs
using UnityEngine;
using System.Collections;

// Test_hello GameObject activated/deactivated checker

public class Test_helloGoChecker : MonoBehaviour {

	float accTime = 0.0f;

	bool preState = false;

	void CheckGameObjectAndRun() {
		GameObject weekly = GameObject.Find ("Test_hello");
		if (weekly == null) { // null if gameobject is deactivated
			preState = false;
			return;
		}
		if (preState == true) {
			return;
		}
		preState = true;

		Test_hello.Test_showHelloMessage ();
	}

	void Update () {
		accTime += Time.deltaTime;
		if (accTime < 0.3f) { // every 300msec
			return;
		}
		accTime = 0.0f;

		CheckGameObjectAndRun ();

	}
}

Test_helloゲームオブジェクトがDeactivatedになっている場合、GameObject.Find()でnullが返るようなので、それを利用した。

デザインにおいて、Actiavted/Deactivatedは以下のようにしておく。監視側は常にActiveでないといけない。

  • Test_hello : deactivated
  • Test_helloGoChecker : activated

実行例

プレイモードで実行後は以下のように Test_hello がDeactivatedになっている。

Main_unity_-150908-udpTimeGraph-PC__Mac___Linux_Standalone__Personal.jpg

インスペクタで Test_helloをActivateにするごとに (下図1) とConsoleに表示される"Hello from Test_hello"の実行回数が増えている (繰り返し処理がされていることが分かる)

Main_unity_-150908-udpTimeGraph-PC__Mac___Linux_Standalone__Personal.jpg

Main_unity_-150908-udpTimeGraph-PC__Mac___Linux_Standalone__Personal.jpg

code

v0.9 @ github

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?