首页 > 代码库 > 【只怕没有几个人能说清楚】系列之一:Awake/Start区别

【只怕没有几个人能说清楚】系列之一:Awake/Start区别

1. Awake方法在脚本对象实例化时执行

2. Start是脚本有效时执行
 
如果在脚本对象实例化后,直接访问脚本对象的属性(初始化后的属性),则属性的初始化需要写在Awake方法
 1 using UnityEngine;
 2 using System.Collections;
 3 public class TestAwakeStart : MonoBehaviour
 4 {
 5     void Create()
 6     {
 7         //Test类的Awake方法在第10行代码后执行,然后再执行第11行的代码,Start方法在当前方法完成后执行
 8         GameObject go = new GameObject("go");
 9         Test test = go.AddComponent<Test>();
10         Debug.Log("test.a = " + test.a);
11     }
12 }
 1 using UnityEngine;
 2 using System.Collections;
 3 public class Test : MonoBehaviour
 4 {
 5     public int a = 0;
 6     void Awake()
 7     {
 8         Debug.Log("Awake");
 9         a = 1;
10     }
11     void Start()
12     {
13         Debug.Log("Start");
14         a = 2;
15     }
16 }

 

【只怕没有几个人能说清楚】系列之一:Awake/Start区别