2015年1月21日 星期三

命名的幽默感-Unity ObjectPool 管理

關於命名的幽默感.
昨天寫了二個腳本,
一個叫 IDontKillMyChild 及 MyParentDonKillMe.
它們主要是用在 ObjectPool 管理時,
例如:
ObjectPool 管理特效物件火球F 時.
1.當敵人A 被火燒, 火球F 會被要求出來加入成為敵人A 的 child 方便跟著敵人移動. (當然也可以不加入為 child 自己去算 transform).
2.然後換場景時, 敵人A 確定用不到了, 我會把敵人A Destroy 掉,
3.但因為火球F 是敵人A 的 child, 所以火球F 也會被Destroy 掉,
4.ObjectPool 裡的東西就這樣被借走的人弄壞了.
所以我就把
1. IDontKillMyChild 掛在敵人A 身上,
2. MyParentDonKillMe 掛在火球F 身上,
3. 然後 IDontKillMyChild 在 OnDestroy 時, 會把身上有 MyParentDonKillMe component 的 child 從自己身上移走.
4. 這樣子他的 child 就可自動免於一死了.
ps. 敵人A 也是被 ObjectPool 管理的, 是確定關卡用不到才會Destroy 掉.

//===  IDontKillMyChild. cs =================
using UnityEngine;
using System.Collections;
public class IDontKillMyChild : MonoBehaviour
 {
void OnDestroy()
{
MyParentDonKillMe[] dks = GetComponentsInChildren<MyParentDonKillMe>(true);
foreach(MyParentDonKillMe dk in dks)
{
dk.gameObject.transform.parent = null;
}
}
}
//===  MyParentDonKillMe. cs =================
using UnityEngine;
using System.Collections;
public class MyParentDonKillMe : MonoBehaviour
{
}

沒有留言:

張貼留言