阻止编辑器退出播放
🍔使用场景
有时候会遇到直接退出播放时导致崩溃,可能是某些插件没清理完导致的。这时可以监听播放状态的更改,及时阻止编辑器退出,然后把该销毁的先销毁了,再退出播放模式。
🌮参考
csharp
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace ZYF
{
/// <summary>
/// 退出播放模式前先销毁所有的播放器,不然可能崩溃
/// </summary>
public class DestroyAllPlayersBeforeExitPlayMode
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void Init()
{
if (Application.isPlaying ==false || Application.isEditor ==false) {
return;
}
//监听播放状态变更
EditorApplication.playModeStateChanged += PlayModelChangedHandler;
}
private static void PlayModelChangedHandler(PlayModeStateChange change)
{
if (change == PlayModeStateChange.ExitingPlayMode)
{
//移除监听,不然会进入死循环
EditorApplication.playModeStateChanged -= PlayModelChangedHandler;
//立即进入播放模式阻止退出
EditorApplication.EnterPlaymode();
//销毁资源
DestroyAllPlayers();
//然后再退出播放
EditorApplication.ExitPlaymode();
}
}
static void DestroyAllPlayers()
{
}
}
}