[Unity] Awake()とStart()の実行タイミング


Awake()とStart()

順番は、Awake()の後に、Start()が実行されるのはご存じの通りだと思います。
では、GameObjectが非アクティブだったり、コンポーネントがdisableだったらどうなるでしょうか?
また、AddComponent()で追加したときは?
そこら辺をまとめました。





Kindle無料漫画ランキング

結論から言うと・・・

Awake()は、GameObjectがアクティブであれば、コンポーネントがenableでもdisable実行されます。
Start()は、GameObjectがアクティブで、コンポーネントがenableでないと実行されません。
AddComponent()で追加したときは、アクティブの場合だと内部でAwake()が呼ばれます。

一覧表


関数

Active

enable

実行

Awake()

true

true


Awake()

true

false


Awake()

false

true

×

Awake()

false

false

×


Start()

true

true


Start()

true

false

×

Start()

false

true

×

Start()

false

false

×





サンプル

今回もサンプルを用意しておいたので一緒にご覧ください。
GetComponentSample.cs
まずはこれを、"Child Object 1~4" にそれぞれ追加して実行してみましょう。
Hierarchyは上の画像を参照のこと。

実行結果


Game Object

Active

enable

Active
実行

enable
実行

Child Object 1

true

true



Child Object 2

false

true

×

×

Child Object 3

true

false


×

Child Object 4

false

false

×

×
インスペクターでアクティブにしたり、enableにするとそのタイミングで実行されますよ。

AddComponent()で追加したときは・・・

ActiveなGameObjectに追加したときは、Awake()がそのまま内部で呼ばれます。
Start()は、Activeでenableの場合そのうち呼ばれますよ。

気をつけるタイミング

[#Unity] GetComponent系の動作
でやったGetComponent関係で、
GetComponentInChildren<T>()
GetComponentInChildren<T>(true)など
を使った場合、Awake()もStart()も実行されていない状態で取得できてしまいます。
また、インスペクターで直接に参照してるコンポーネントでも同じです。
Awake()やStart()が実行されている前提でGetComponent関係を使うときは注意しましょう。






コードのすべてはこちら

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetComponentSample : MonoBehaviour
{
private bool Flag { get; set; }
private void Awake()
{
Debug.Log($"{name} : in Awake");
}
void Start()
{
Debug.Log($"{name} : in Start");
Debug.Log($"{name} : current position is {GetComponent<Transform>().position}");
Debug.Log($"{name} : child name is {GetComponentInChildren<GetComponentSample>()?.name}");
Debug.Log($"{name} : child (includeActive) name is {GetComponentInChildren<GetComponentSample>(true)?.name}");
Debug.Log($"{name} : parent name is {GetComponentInParent<GetComponentSample>()?.name}");
Debug.Log($"{name} : current component length is {GetComponents<Transform>()?.Length}");
Debug.Log($"{name} : children component length is {GetComponentsInChildren<Transform>()?.Length}");
Debug.Log($"{name} : children (includeActive) component length is {GetComponentsInChildren<Transform>(true)?.Length}");
Debug.Log($"{name} : prarent component length is {GetComponentsInParent<Transform>()?.Length}");
}
void Update()
{
if (!Flag)
Debug.Log($"{name} : in Update");
Flag = true;
}
}

以上でした

0 件のコメント :

コメントを投稿