unity 方法的调用顺序
- 正常的是
-
Awake>OnEnable>Start>FixedUpdate>Update>LateUpadate>OnDisable>OnDestory
-
- 如果这时在脚本里面创建个新方法 Init, 在另个脚本中调用这个Init方法
- 执行顺序结果
-
Awake>OnEnable>Init>Start>FixedUpdate>Update>LateUpadate>OnDisable>OnDestory
- 结果发现 Init这个方法会在 OnEnable之后 Start之前
- (所以有时候你在Start里面实例化的物体 在init里面会报错,这时候 你只需在OnEnable里面实例化那个物体就好了,但是需要注意的是OnEnable游戏物体/脚本组件激活时调用(会反复触发))
- 实验代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VoidOrder : MonoBehaviour
{
private void Awake()
{
Debug.Log("Awake");
}
private void OnEnable()
{
Debug.Log("OnEnable");
}
void Start()
{
Debug.Log("Start");
}
bool isone = false;//让Update 只一次
void Update()
{
if (!isone)
{
isone = true;
Debug.Log("Update");
}
}
public void Init()
{
Debug.Log("Init");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Order : MonoBehaviour
{
void Start()
{
VoidOrder Vo= gameObject.AddComponent<VoidOrder>();
Vo.Init();
}
}
输出结果