Awake函数和Start函数的区别

来源:互联网 发布:结构优化设计 王光远 编辑:程序博客网 时间:2024/06/05 15:24

先说结论:

      从调用的顺序来看。

      Awake在脚本实例被创建的时候(无论脚本组件是否被激活),在所有游戏对象被初始化之后执行。

      Start在脚本的Enable属性被开启之后,在所有的Awake函数被调用之后,在update之前调用。

      一般在Awake函数中对创建的变量初始化,在Start函数中对变量进行赋值。

下面放例子说明:

maintest.cs:

using System.Collections;using System.Collections.Generic;using UnityEngine;public class maintest : MonoBehaviour {    GameObject obj;    // Use this for initialization    void Awake()    {        obj = GameObject.Find ("Cube”);/*如果在Awake函数里初始化obj,是不会输出NULL Object的*/    }    void Start () {        //obj = GameObject.Find ("Cube");/*如果在Start函数里初始化obj,要输出NULL Object*/    }        // Update is called once per frame    void Update () {                    }    public void GetCompnet(GameObject go){        if (obj == null) {            Debug.LogError ("Null Object!\n");        } else {            go.transform.parent = obj.transform;        }    }}

main.cs:

using System.Collections;using System.Collections.Generic;using UnityEngine;public class main : MonoBehaviour {    public GameObject otherObj;    maintest test;    // Use this for initialization    void Start () {        test = otherObj.AddComponent<maintest> ();/*执行此句时,会调用Awake函数,不会调用Start函数*/        test.GetCompnet (otherObj);    }        // Update is called once per frame    void Update () {            }}

      当我们把maintest脚本组件禁用掉之后,如果在Awake函数里初始化obj,是不会输出NULL Object的,而在Start函数里初始化就会。

      当我们调用加载组件函数加载脚本组件时,

            AddComponent<maintest>();

      Awake函数会被调用,Start不会。



0 0