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宣言としている。
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(下記)を用意
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になっている。
インスペクタで Test_helloをActivateにするごとに (下図1) とConsoleに表示される"Hello from Test_hello"の実行回数が増えている (繰り返し処理がされていることが分かる)