Awake 在加载脚本实例时调用。
Awake 用于在游戏启动之前初始化任何变量或游戏状态。
在脚本实例的生命周期内仅调用 Awake 一次。
所有对象初始化之后,将调用 Awake,以便您可以使用 GameObject.FindWithTag 等安全地与其他对象通信或者对其进行查询。
在对象之间,按随机顺序调用每个游戏对象的 Awake。因此,您应该使用 Awake 在脚本之间设置引用,并使用 Start 来回传递任何信息。
始终先调用 Awake,然后才调用任何 Start
函数。这让您可以对脚本的初始化进行排序。
Awake 不能充当协程。
注意:请使用 Awake 来代替构造函数进行初始化,因为组件的序列化状态在构造时是未定义的。
与构造函数一样,仅调用 Awake 一次。
using UnityEngine;
public class ExampleClass : MonoBehaviour { private GameObject target;
void Awake() { target = GameObject.FindWithTag("Player"); } }
对于未激活的 GameObject,调用 GameObject.SetActive 可以将其激活。
以下两个脚本协同工作。使用名为 Cube1 和 Cube2 的两个游戏对象。Example1.cs 是 Cube1 的脚本。使用 Inspector 左上角的按钮,将该脚本标记为非活动状态。这意味着将隐藏 Cube1。将 Cube2 标记为活动状态。然而,Cube1 是 Cube2 的公共游戏对象。Example2 脚本可以激活 Cube1,并使它执行 Example1.cs 脚本中的 Awake 函数。
using UnityEngine;
// Make sure that Cube1 is assigned this script and is inactive at the start of the game.
public class Example1 : MonoBehaviour { void Awake() { Debug.Log("Awake"); }
void Start() { Debug.Log("Example1"); }
void Update() { if (Input.GetKeyDown("b")) { print("b key was pressed"); } } }
Example2。此示例将调用 Example1 中的 Awake。空格键用于执行此操作:
using UnityEngine;
public class Example2 : MonoBehaviour { // GO has Example1 script assigned to it so is Cube1 public GameObject GO;
void Start() { Debug.Log("Example2"); }
// allow Cube1 to activated just once private bool activateGO = true;
void Update() { if (activateGO == true) { if (Input.GetKeyDown("space")) { Debug.Log("space key was pressed"); GO.SetActive(true); activateGO = false; } } } }
Awake 不能作为协同程序使用。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.