Unity中Awake()和Start()的本质区别

Unity中Awake()和Start()的本质区别

  • Awake():Awake is called when the script instance is being loaded.
  • Start():Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.

区别总结:

  • Awake()是在脚本对象实例化时被调用的,而Start()是在对象的第一帧时被调用的,而且是在Update()之前。
  • Awake()用于脚本初始化,在脚本的生命周期中只执行一次。

创建测试脚本

using UnityEngine;

public class test1 : MonoBehaviour
{
    
    
    // Start is called before the first frame update
    void Start()
    {
    
    
#if true
        GameObject dynaGO = new GameObject("test2");
        dynaGO.AddComponent<test2>();
#else
        Object prefab = Resources.Load("test2");
        Object instance = GameObject.Instantiate(prefab);
#endif
    }
}

断点

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test2 : MonoBehaviour
{
    
    
    void Awake()
    {
    
    

    }

    // Start is called before the first frame update
    void Start()
    {
    
    
        
    }

    // Update is called once per frame
    void Update()
    {
    
    
        
    }
}

以下是使用AddComponent()方法时,test2:Awake()的调用堆栈:
在这里插入图片描述
下面是使用加载prefab的方式时,test2:Awake()的调用堆栈:
在这里插入图片描述
以下是test2:Start()的调用堆栈:
在这里插入图片描述

结论

  • 脚本的一些成员,如果想在创建之后的代码中立即使用,则必须写在Awake()里面;
  • 当关卡加载时,脚本的Awake的次序是不能控制的;至于在关卡加载时,对象实例化和Awake()的调用关系,得看源码才知道了。

猜你喜欢

转载自blog.csdn.net/qq_40513792/article/details/111039095