首先创建测试项目:

这里我选择了2D,其实都可以,之后可以在项目中修改。
修改方法:

进入正题。
首先看一下官方提供的>手册和>脚本API文档。
创建C#脚本文件并打开:

默认的脚本文件为以下格式:
- 1 using System.Collections;
- 2 using System.Collections.Generic;
- 3 using UnityEngine;
- 4
- 5 public class TestScript : MonoBehaviour
- 6 {
- 7 // Start is called before the first frame update
- 8 void Start()
- 9 {
- 10
- 11 }
- 12
- 13 // Update is called once per frame
- 14 void Update()
- 15 {
- 16
- 17 }
- 18 }
Start( )、Update( )都是事件函数。去查一下事件函数有哪些。>事件函数的执行顺序(Order of Execution for Event Function)
这里官方提供了一个叫脚本生命周期流程图(Script lifecycle flowchart)的东西。(PS:好像版本更新导致现在的和以前的不太一样,所以最好跟着官方的文档来。)

那就从事件函数??开始??。
Awake():
- 1 void Awake() // flowchart上是处于Initialization段也就是初始化阶段执行的事件函数。
- 2 {
- 3 Debug.Log("Awake"); // 控制台输出。
- 4 }

- Awake: This function is always called before any Start functions and also just after a prefab
is instantiated. (If a GameObject is inactive during start up Awake is not called until it is made active.)
这里就是说Awake()最先调用,从图上位置也能看出它的地位。(当一个GameObject在启动的时候不是活动状态,那么Awake()也不会调用,直到它被置为活动状态。)
这里测试一下常用的事件函数以及它们的执行顺序,其它事件函数以后用到再添加进来。
- 1 using System.Collections;
- 2 using System.Collections.Generic;
- 3 using UnityEngine;
- 4
- 5 public class TestScript : MonoBehaviour
- 6 {
- 7 void Awake() // flowchart上是处于Initialization段也就是初始化阶段执行的事件函数。
- 8 {
- 9 Debug.Log("Awake"); // 控制台输出。
- 10 }
- 11
- 12 void OnEnable()
- 13 {
- 14 Debug.Log("OnEnable");
- 15 }
- 16
- 17 void Reset() // 当附加于一个GameObject或手动Reset时调用。(不能在PlayMode时)
- 18 {
- 19 Debug.Log("Reset");
- 20 }
- 21
- 22 void Start() // 程序开始时,只调用一次。
- 23 {
- 24 Debug.Log("Start");
- 25 }
- 26
- 27 void Update() // 字面意思,更新,但是会受实际性能影响。
- 28 {
- 29 Debug.Log("Update");
- 30 }
- 31
- 32 void FixedUpdate() // 更加适合物理运动的更新。
- 33 {
- 34 Debug.Log("FixedUpdate");
- 35 }
- 36
- 37 void LateUpdate() // 在Update()后执行的函数。
- 38 {
- 39 Debug.Log("LateUpdate");
- 40 }
- 41
- 42 void OnDisable() // 和OnEnable()是一对儿哒~
- 43 {
- 44 Debug.Log("OnDisable");
- 45 }
- 46
- 47 void OnApplicationQuit() // 程序退出时 执行顺序(OnApplication()->OnDisable()->OnDestroy());
- 48 {
- 49 Debug.Log("OnApplicationQuit");
- 50 }
- 51 /// <summary>
- 52 /// OnDestroy: This function is called after all frame updates for the last frame of the object’s existence
- 53 /// (the object might be destroyed in response to Object.Destroy or at the closure of a scene).
- 54 /// </summary>
- 55 void OnDestroy() // 销毁
- 56 {
- 57 Debug.Log("OnDestroy");
- 58 }
- 59 }
运行效果:
