描述

在首次调用任何 Update 方法之前启用脚本时,在帧上调用 Start。

类似于 Awake 函数,Start 在脚本生命周期内仅调用一次。但是,不管是否启用脚本,初始化脚本对象时都会调用 Awake。如果在初始化时未启用脚本,则可以在与 Awake 不同的帧上调用 Start。

在调用任何对象的 Start 函数之前,将在场景中的所有对象上调用 Awake 函数。如果对象 A 的初始化代码需要依赖于已经初始化的对象 B,则这一点会非常有用;此时,B 的初始化应在 Awake 中完成,A 则应在 Start 中完成。

在游戏过程中实例化对象时,Awake 函数在 Scene 对象的 Start 函数完成后调用。

using UnityEngine;
using System.Collections;

// The ExampleClass starts with Awake. The GameObject class has activeSelf // set to false. When activeSelf is set to true the Start() and Update() // functions will be called causing the ExampleClass to run. // Note that ExampleClass (Script) in the Inspector is turned off. It // needs to be ticked to make script call Start.

public class ExampleClass : MonoBehaviour { private float update;

void Awake() { Debug.Log("Awake"); update = 0.0f; }

IEnumerator Start() { Debug.Log("Start1"); yield return new WaitForSeconds(2.5f); Debug.Log("Start2"); }

void Update() { update += Time.deltaTime; if (update > 1.0f) { update = 0.0f; Debug.Log("Update"); } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961