[Unity]编辑器中第一次结束游戏后第二次开始游戏崩溃的问题

最近在使用unity编辑器的过程中,总是遇到第二次运行游戏unity直接crash的问题,甚为苦恼。

经反复试验,发现在第一次游戏结束后,在编辑器模式下切换一下场景再切换回开始场景后运行游戏能顺利执行。

知道了怎么避免,那么只需要Edirot代码来自动化这一过程了。监听编辑器退出游戏运行的事件,在游戏退出的时候自动切换场景就可以了。

查看了一下文档,可以监听EditorApplication.playModeStateChanged, 在监听到playModeStateChanged EnteredEditMode到时候,切换场景就可以了(因为发现立马切换会有东西没有清理完而报错,所以延后了几帧)。

//Author: zhiheng.shao
//E-mail: [email protected]
//Blog: http://blog.csdn.net/rickshaozhiheng
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;

[InitializeOnLoadAttribute]
public static class FixUnityRePlayCrashBug
{
    /// <summary>
    /// 游戏EnteredEditMode之后执行切换场景等待的帧数
    /// </summary>
    private const int WATI_FRAMES = 2;

    /// <summary>
    /// 当前已等待的帧数
    /// </summary>
    private static int currentWaitFrames = 0;

    /// <summary>
    /// 用来临时切换场景用的场景的路径
    /// </summary>
    private const string tempScenePath = "Assets/Yummy/GameAssets/Scene/YourOwnTempScene.unity";

    /// <summary>
    /// 游戏启动的场景的路径
    /// </summary>
    private const string launcherScenePath = "Assets/Yummy/GameAssets/Scene/YourOwnLauncherScene.unity";

    // register an event handler when the class is initialized
    static FixUnityRePlayCrashBug()
    {
        EditorApplication.playModeStateChanged += OnplayModeStateChanged;
    }

    /// <summary>
    /// playModeStateChanged监听
    /// </summary>
    /// <param name="state"></param>
    private static void OnplayModeStateChanged(PlayModeStateChange state)
    {
        if (state == PlayModeStateChange.EnteredEditMode)
        {
            currentWaitFrames = 0;
            EditorApplication.update += Update;
        }
    }

    private static void Update() {
        currentWaitFrames++;
        if (currentWaitFrames >= WATI_FRAMES) {
            ChangeScenes();

            EditorApplication.update -= Update;
        }
    }

    /// <summary>
    /// 切换场景
    /// </summary>
    private static void ChangeScenes() {
        EditorSceneManager.OpenScene(tempScenePath);
        EditorSceneManager.OpenScene(launcherScenePath);
        Debug.Log("Rechange To Launcher Scene!");
        currentWaitFrames = 0;
    }
}

猜你喜欢

转载自blog.csdn.net/rickshaozhiheng/article/details/79091472
今日推荐