引言
Unity项目中可能会存在一些需要初始化的内容,比如说SDK、存档等,利用RuntimeInitializeOnLoadMethodAttribute就可以很方便的实现而不需担心优先级等问题。
使用方法:在静态方法前加上此特性。注意是静态方法。 还有一点就是不需要挂在场景中也能触发此方法。
示例代码:
using UnityEngine;
public class InitTest : MonoBehaviour
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void OnBeforeSceneLoadRuntimeMethod ()
{
Debug.Log("Before scene loaded");
}
void Awake()
{
Debug.Log("Awake");
}
void OnEnable()
{
Debug.Log("OnEnable");
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void OnAfterSceneLoadRuntimeMethod()
{
Debug.Log("After scene loaded");
}
[RuntimeInitializeOnLoadMethod]
static void OnRuntimeMethodLoad()
{
Debug.Log("RuntimeMethodLoad: After scene loaded");
}
void Start()
{
Debug.Log("Start");
}
}
输出: