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

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

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

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

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

//Author: zhiheng.shao
//E-mail: zhiheng.rick@gmail.com
//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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值