Configurable Enter Play Mode(播放模式启用可配置化)功能

在File > Project Settings > Editor下找到Enter Play Mode Options(播放模式启用选项),其中的reload Domain(重新加载域)和reload Scene(重新加载场景)变为可用状态。

当禁止重新加载域时,多次进入播放模式时脚本中的静态字段不会重置为初始值。
可以使用[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] 设置,指定重置数值,确保在禁用域重新加载时计数器能正确重置。

using UnityEngine;

public class StaticCounterExampleFixed : MonoBehaviour{
	static int counter = 0;
 
	[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
	static void Init(){
		Debug.Log("Counter reset.");
		counter = 0;  
	}
 
	void Update(){
		if (Input.GetButtonDown("Jump")){
		counter++;
		Debug.Log("Counter: " + counter);
		}
	}
}

当禁用了域重新加载,Unity不会在退出播放模式时注销静态事件处理器上的方法。
举例来说,在编辑器中第一次播放项目时,方法会被正常注册。然而,在第二次播放项目时,这些方法会在第一次注册方法的基础上再注册一次,于是,事件在触发时会调用两次。
可以使用[RuntimeInitializeOnLoadMethod]属性,具体地将方法注销,防止其被注册两次:

using UnityEngine;

public class StaticEventExampleFixed : MonoBehaviour{
	[RuntimeInitializeOnLoadMethod]
	static void RunOnStart(){
    	Debug.Log("Unregistering quit function");
    	Application.quitting -= Quit;
	}
 
	void Start(){
    	Debug.Log("Registering quit function");
    	Application.quitting += Quit;
	}
 
	static void Quit(){
    	Debug.Log("Quitting the Player");
	}
}

RuntimeInitializeOnLoadMethod方法执行顺序

private void Awake(){
	Debug.Log("Awake");
}

#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod]
private static void OnLoadInit(){
	Debug.Log("OnLoadInit");
}
#endif

private void Start(){
	Debug.Log("Start");
}
//执行顺序:Awake->OnLoadInit->Start

原文地址:https://connect.unity.com/p/ru-he-zai-unity-2019-3zhong-geng-kuai-di-jin-ru-bo-fang-mo-shi?from=timeline

原文地址:https://www.cnblogs.com/kingBook/p/12456535.html