unity 使用GameObject.SetActive(true)激活對象時,會在SetActive內部調用Awake和OnEnable函數


using System;
using UnityEngine;
public class Foo:MonoBehaviour{
    private void Awake(){
        Debug.Log("Foo.Awake();");
    }
    private void OnEnable(){
        Debug.Log("Foo.OnEnable();");
    }

    private void Start(){
        Debug.Log("Foo.Start();");
    }
}
using System;
using UnityEngine;

public class Test:MonoBehaviour{
    
    public GameObject foo2;//Hierarchy面板中綁定Foo腳本的GameObject(未激活、在綁定Test腳本的GameObject上方)
    
    private void Start(){
        //Test1();
        Test2();
    }
    
    private void Test1(){
        GameObject fooGameObject=new GameObject("Foo",typeof(Foo));
        //創建GameObject后即使立刻SetActive(false),綁定代碼中的Awake與OnEnable函數也會觸發
        fooGameObject.SetActive(false);
        /*output:
        Foo.Awake();
        Foo.OnEnable();
        */
        
        Debug.Log("fooGameObject.SetActive(true); Start");
        fooGameObject.SetActive(true);
        Debug.Log("fooGameObject.SetActive(true); End");
        //在SetActive(true)函數內調用OnEnable函數
        /*output:
        fooGameObject.SetActive(true); Start
        Foo.OnEnable();
        fooGameObject.SetActive(true); End
        Foo.Start();
        */
    }
    
    private void Test2(){
        Debug.Log("fooGameObject.SetActive(true); Start");
        foo2.SetActive(true);
        Debug.Log("fooGameObject.SetActive(true); End");
        //在SetActive(true)函數內調用Awake與OnEnable函數
        /*output:
         fooGameObject.SetActive(true); Start
         Foo.Awake();
         Foo.OnEnable();
         fooGameObject.SetActive(true); End
         Foo.Start();
         */
         
    }
}

總結:
當調用GameObject. SetActive(true)方法激活對象時,會在方法內部調用Awake和OnEnable函數,然后才調用Start函數。
Awake與Start函數不管吊銷和激活多少次都只會調用一次。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM