2015年4月7日火曜日

unity Instantiate後、スクリプトから登録したparentが使えるタイミングの確認

スクリプトからプレハブの実体を生成し、子に設定した際、
子から親のポジションなど変数が利用できるタイミングを確認した。


〇 親にアタッチしたスクリプト

public class TestParent : MonoBehaviour {

    public GameObject child_prefab;    //インスペクターから子プレハブを登録

 void Update () {
        Debug.Log(Time.frameCount + " " + name + " : Update Start ");
        if (Input.GetKeyDown("space"))
        {
            Debug.Log(Time.frameCount + " " + name + " : Instatiate ");
            GameObject go = Instantiate(child_prefab);
            Debug.Log(Time.frameCount + " " + name + " : set Parent ");
            go.transform.parent = transform;
        }
        Debug.Log(Time.frameCount + " " + name + " : Update End ");
 }
}


〇 子プレハブにアタッチしたスクリプト

public class TestChild : MonoBehaviour {

    void Awake()
    {
        Debug.Log(Time.frameCount + " " + name + " : Awake ");
        if (transform.parent != null) Debug.Log(Time.frameCount + " : Parent is not null ********************");
    }

 void Start () {
        Debug.Log(Time.frameCount + " " + name + " : Start ");
        if (transform.parent != null) Debug.Log(Time.frameCount + " : Parent is not null ********************");
    }

 void Update () {
        Debug.Log(Time.frameCount + " " + name + " : Update ");
        if (transform.parent != null) Debug.Log(Time.frameCount + " : Parent is not null ********************");
    }
}


〇 結果



154フレーム目にスペースキーが押された。
154フレームの流れは

・親のUpdateが開始し、
 Instantiateで子を生成
・子のAwakeが起動
・親が子にParentをセットし、
 親のUpdateが終了
・子のStartが起動、ここでparentが有効

となっており、子のStart時にはparentを使用できることが確認できた。



*を連続で並べたのはログから見つけ易くするため。
Insta"n"tiate 脱字です。

0 件のコメント:

コメントを投稿