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函数不管吊销和激活多少次都只会调用一次。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值