本文章由cartzhang编写,转载请注明出处。 全部权利保留。

文章链接:http://blog.csdn.net/cartzhang/article/details/51055584

作者:cartzhang

一、Unity关卡

Unity 使用过程中关卡载入和卸载是大多数三维引擎都要提供的基本功能。

由于关卡切换在游戏中很经常使用。

在之前的版本号中Unity的关卡切换使用的是:

  1. Application.loadedLevel()

看看Application类,此时这个类的功能比較繁杂。比較多。仅仅看与关卡相关的:


  1. [Obsolete("Use SceneManager.LoadScene")]
  2. public static void LoadLevel(string name);
  3. [Obsolete("Use SceneManager.LoadScene")]
  4. public static void LoadLevel(int index);
  5. [Obsolete("Use SceneManager.LoadScene")]
  6. public static void LoadLevelAdditive(string name);
  7. [Obsolete("Use SceneManager.LoadScene")]
  8. public static void LoadLevelAdditive(int index);
  9. //
  10. // 摘要:
  11. // ///
  12. // Unloads all GameObject associated with the given scene. Note that assets are
  13. // currently not unloaded, in order to free up asset memory call Resources.UnloadAllUnusedAssets.
  14. // ///
  15. //
  16. // 參数:
  17. // index:
  18. // Index of the scene in the PlayerSettings to unload.
  19. //
  20. // scenePath:
  21. // Name of the scene to Unload.
  22. //
  23. // 返回结果:
  24. // ///
  25. // Return true if the scene is unloaded.
  26. // ///
  27. [Obsolete("Use SceneManager.UnloadScene")]
  28. public static bool UnloadLevel(string scenePath);
  29. //
  30. // 摘要:
  31. // ///
  32. // Unloads all GameObject associated with the given scene. Note that assets are
  33. // currently not unloaded, in order to free up asset memory call Resources.UnloadAllUnusedAssets.
  34. // ///
  35. //
  36. // 參数:
  37. // index:
  38. // Index of the scene in the PlayerSettings to unload.
  39. //
  40. // scenePath:
  41. // Name of the scene to Unload.
  42. //
  43. // 返回结果:
  44. // ///
  45. // Return true if the scene is unloaded.
  46. // ///
  47. [Obsolete("Use SceneManager.UnloadScene")]
  48. public static bool UnloadLevel(int index);

这是之前的Application中的关卡的载入和卸载。

当然如今在新版本号(Unity5.3以上)中,有了新的变化,那就是SceneManager类了处理。

二、Untiy的SceneManager类

自从Unity5.3版本号,Unity 的关卡切换就加入了新的SceneManager的类来处理。

当然要安装过了Unity文档帮助。而且给以下路径一样。就能够知道在本地打开。

本地链接:

file:///C:/Program%20Files/Unity5.3.0/Editor/Data/Documentation/en/Manual/UpgradeGuide53.html

也能够在Unity中搜索SceneManager来查看。

  1. #region 程序集 UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
  2. // H:\Unity\UnityProject\ShiftLevels\Library\UnityAssemblies\UnityEngine.dll
  3. #endregion
  4. using UnityEngine.Internal;
  5. namespace UnityEngine.SceneManagement
  6. {
  7. //
  8. // 摘要:
  9. // ///
  10. // Scene management at run-time.
  11. // ///
  12. public class SceneManager
  13. {
  14. public SceneManager();
  15. public static int sceneCount { get; }
  16. //
  17. public static int sceneCountInBuildSettings { get; }
  18. public static Scene GetActiveScene();
  19. public static Scene[] GetAllScenes();
  20. // 參数:
  21. // index:
  22. // Index of the scene to get. Index must be greater than or equal to 0 and less
  23. // than SceneManager.sceneCount.
  24. public static Scene GetSceneAt(int index);
  25. // 返回结果:
  26. // ///
  27. // The scene if found or an invalid scene if not.
  28. // ///
  29. public static Scene GetSceneByName(string name);
  30. // Searches all scenes added to the SceneManager for a scene that has the given
  31. // asset path.
  32. // ///
  33. //
  34. // 參数:
  35. // scenePath:
  36. // Path of the scene. Should be relative to the project folder. Like: "AssetsMyScenesMyScene.unity".
  37. public static Scene GetSceneByPath(string scenePath);
  38. [ExcludeFromDocs]
  39. public static void LoadScene(int sceneBuildIndex);
  40. [ExcludeFromDocs]
  41. public static void LoadScene(string sceneName);
  42. // 參数:
  43. // sceneName:
  44. // Name of the scene to load.
  45. //
  46. // sceneBuildIndex:
  47. // Index of the scene in the Build Settings to load.
  48. //
  49. // mode:
  50. // Allows you to specify whether or not to load the scene additively. See SceneManagement.LoadSceneMode
  51. // for more information about the options.
  52. public static void LoadScene(int sceneBuildIndex, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);
  53. // 參数:
  54. // sceneName:
  55. // Name of the scene to load.
  56. //
  57. // sceneBuildIndex:
  58. // Index of the scene in the Build Settings to load.
  59. //
  60. // mode:
  61. // Allows you to specify whether or not to load the scene additively. See SceneManagement.LoadSceneMode
  62. // for more information about the options.
  63. public static void LoadScene(string sceneName, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);
  64. [ExcludeFromDocs]
  65. public static AsyncOperation LoadSceneAsync(int sceneBuildIndex);
  66. [ExcludeFromDocs]
  67. public static AsyncOperation LoadSceneAsync(string sceneName);
  68. // 參数:
  69. // sceneName:
  70. // Name of the scene to load.
  71. //
  72. // sceneBuildIndex:
  73. // Index of the scene in the Build Settings to load.
  74. //
  75. // mode:
  76. // If LoadSceneMode.Single then all current scenes will be unloaded before loading.
  77. public static AsyncOperation LoadSceneAsync(int sceneBuildIndex, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);
  78. // 參数:
  79. // sceneName:
  80. // Name of the scene to load.
  81. //
  82. // sceneBuildIndex:
  83. // Index of the scene in the Build Settings to load.
  84. //
  85. // mode:
  86. // If LoadSceneMode.Single then all current scenes will be unloaded before loading.
  87. public static AsyncOperation LoadSceneAsync(string sceneName, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);
  88. //
  89. // 參数:
  90. // sourceScene:
  91. // The scene that will be merged into the destination scene.
  92. //
  93. // destinationScene:
  94. // Existing scene to merge the source scene into.
  95. public static void MergeScenes(Scene sourceScene, Scene destinationScene);
  96. //
  97. // 摘要:
  98. // ///
  99. // Move a GameObject from its current scene to a new scene. /// It is required that
  100. // the GameObject is at the root of its current scene.
  101. // ///
  102. //
  103. // 參数:
  104. // go:
  105. // GameObject to move.
  106. //
  107. // scene:
  108. // Scene to move into.
  109. public static void MoveGameObjectToScene(GameObject go, Scene scene);
  110. //
  111. // 返回结果:
  112. // ///
  113. // Returns false if the scene is not loaded yet.
  114. // ///
  115. public static bool SetActiveScene(Scene scene);
  116. // ///
  117. public static bool UnloadScene(string sceneName);
  118. //
  119. // 摘要:
  120. // ///
  121. // Unloads all GameObjects associated with the given scene. Note that assets are
  122. // currently not unloaded, in order to free up asset memory call Resources.UnloadAllUnusedAssets.
  123. // ///
  124. //
  125. // 參数:
  126. // sceneBuildIndex:
  127. // Index of the scene in the Build Settings to unload.
  128. //
  129. // sceneName:
  130. // Name of the scene to unload.
  131. //
  132. // 返回结果:
  133. // ///
  134. // Returns true if the scene is unloaded.
  135. // ///
  136. public static bool UnloadScene(int sceneBuildIndex);
  137. }
  138. }

注意的是这里面还有能够带对象来在关卡中移动的,还有穿越功能啊!

!哈哈

三、5.3的实现代码

上代码:

  1. /**************************************************************************
  2. Copyright:@cartzhang
  3. Author: cartzhang
  4. Date: 2016-04-01
  5. Description:载入关卡。能够分组载入和卸载。
  6. 使用Unity版本号为5.3.0.
  7. 由于里面使用了场景管理的一个类,这个类在5.3.0以上版本号才加入的。
  8. 測试操作:使用空格键来切换场景。然后间隔5秒后才開始卸载。
  9. **************************************************************************/
  10. using UnityEngine;
  11. using System.Collections;
  12. using UnityEngine.SceneManagement;
  13. [System.Serializable]
  14. public class LevelOrder
  15. {
  16. [Header("每组关卡名称")]
  17. public string[] LevelNames;
  18. }
  19. public class ChangLevelsHasMain : MonoBehaviour
  20. {
  21. [Header("全部关卡列表")]
  22. public LevelOrder[] levelOrder;
  23. private static int index;
  24. private int totalLevels = 0;
  25. private int levelOrderLength;
  26. void Start ()
  27. {
  28. for (int i = 0; i < levelOrder.Length; i++)
  29. {
  30. totalLevels += levelOrder[i].LevelNames.Length;
  31. }
  32. if (totalLevels != SceneManager.sceneCountInBuildSettings)
  33. {
  34. }
  35. levelOrderLength = levelOrder.Length;
  36. }
  37. // Update is called once per frame
  38. void Update ()
  39. {
  40. if (Input.GetKeyDown(KeyCode.Space))
  41. {
  42. bool isOk = LoadNextLevels();
  43. if (isOk)
  44. {
  45. InvokeRepeating("UnloadLastLevel", 2.0f, 5);
  46. }
  47. }
  48. }
  49. bool LoadNextLevels()
  50. {
  51. bool bResult = true;
  52. //index = index % levelOrderLength;
  53. if (index < 0 || index >= levelOrderLength)
  54. {
  55. bResult = false;
  56. return bResult;
  57. }
  58. int LoadTimes = levelOrder[index].LevelNames.Length;
  59. for (int i = 0; i < LoadTimes; i++)
  60. {
  61. SceneManager.LoadSceneAsync(levelOrder[index].LevelNames[i], LoadSceneMode.Additive);
  62. }
  63. return bResult;
  64. }
  65. void UnloadLastLevel()
  66. {
  67. if (index == 0)
  68. {
  69. index++;
  70. CancelInvoke("UnloadLastLevel");
  71. return;
  72. }
  73. // 上一組的關卡
  74. int TmpLast = (index - 1) >= 0 ?
  75. (index - 1) : levelOrderLength - 1;
  76. int LoadTimes = levelOrder[index].LevelNames.Length;
  77. for (int i = 0; i < LoadTimes; i++)
  78. {
  79. Scene Tmp = SceneManager.GetSceneByName(levelOrder[index].LevelNames[i]);
  80. if (!Tmp.isLoaded)
  81. {
  82. return;
  83. }
  84. }
  85. // 下一關卡全部加載完畢後。卸載之前關卡
  86. for (int i = 0; i < levelOrder[TmpLast].LevelNames.Length; i++)
  87. {
  88. SceneManager.UnloadScene(levelOrder[TmpLast].LevelNames[i]);
  89. }
  90. index++;
  91. CancelInvoke("UnloadLastLevel");
  92. }
  93. }

就这样就能够了。

代码主要是按组来载入关卡。然后按组来卸载。

測试中,按下空格键来载入。每组关卡在一定时间后,(这里设置的5秒)自己主动卸载前一组关卡。这里主地图是不卸载的,会一直存在的。

怎么设置的呢?首先须要在Build setting中中把全部要处理的关卡放进来。要不就会在载入过程中报错。

例如以下图:

然后把代码挂在主地图的随意对象对象上就能够了。

四、測试结果

随意做了几张地图。不那么好看。

可是功能很明显。

第一组:



第二组



第三组

參考

file:///C:/Program%20Files/Unity5.3.0/Editor/Data/Documentation/en/Manual/UpgradeGuide53.html

追加Github地址:https://github.com/cartzhang/ShiftLevels

————————–THE———END————–

若有问题。请随时联系!。

很感谢!!

你在桥上看风景。我在楼里加班!

Unity5的关卡切换的更多相关文章

  1. UE4 difference between servertravel and openlevel(多人游戏的关卡切换)

    多人游戏的关卡切换分为无缝和非无缝.非无缝切换时,客户端将跟服务器断开连接,然后重新连接到同一个服务器,服务器则加载一个新地图.无缝切换不会发生这样的情况. 有三个函数供我们使用:UEngine::B ...

  2. 【UE4 C++】关卡切换、流关卡加载卸载

    切换关卡 基于 UGameplayStatics:: OenLevel UGameplayStatics::OpenLevel(GetWorld(), TEXT("NewMap") ...

  3. UGUI_游戏菜单场景切换

    事件委托 GameManger(空物体)+GameManger脚本——重要的方式 public class GameManger : MonoBehaviour { public void OnSta ...

  4. Unity AssetBundles and Resources指引 (四) AssetBundle使用模式

    本文内容主要翻译自下面这篇文章 https://unity3d.com/cn/learn/tutorials/topics/best-practices/guide-assetbundles-and- ...

  5. Unity项目 - MissionDemolition 愤怒的小鸟核心机制

    目录 游戏原型 项目演示 绘图资源 代码实现 注意事项 技术探讨 参考来源 游戏原型 爆破任务 MissionDemolition 是一款核心机制类似于愤怒的小鸟的游戏,玩家将用弹弓发射炮弹,摧毁城堡 ...

  6. 《InsideUE4》-8-GamePlay架构(七)GameMode和GameState

    我的世界,我做主 引言 上文我们说到在Actor层次,UE用Controller来充当APawn的逻辑控制者,也有了可以接受玩家输入的PlayerController,和能自行行动的AIControl ...

  7. Unity内存理解(转)

    Unity3D 里有两种动态加载机制:一个是Resources.Load,另外一个通过AssetBundle,其实两者区别不大. Resources.Load就是从一个缺省打进程序包里的AssetBu ...

  8. 【转载】Unity 优雅地管理资源,减少占用内存,优化游戏

    转自:星辰的<Unity3D占用内存太大的解决方法> 最近网友通过网站搜索Unity3D在手机及其他平台下占用内存太大. 这里写下关于Unity3D对于内存的管理与优化. Unity3D  ...

  9. Unity3D占用内存太大的解决方法

    原地址:http://www.cnblogs.com/88999660/archive/2013/03/15/2961663.html 最近网友通过网站搜索Unity3D在手机及其他平台下占用内存太大 ...

随机推荐

  1. LNOI2019划水记

    十二省联考命题组温馨提醒您: 数据千万条,清空第一条. 多测不清空,爆零两行泪. NOIp2018差点退役的游记 $Flag$拔了. $LNOI2019$划水记: $Day0$: 早上八点起床,一直颓 ...

  2. 聊聊svg

    来源:SVG的用法 补充 CANVAS产生的dom数量比SVG要少 SVG可以使用css设置动画样式 对于动画性能来说,不能说svg或canvas谁更优,而是要看情况: SVG 是一种使用 XML 描 ...

  3. 基于flask的网页聊天室(二)

    基于flask的网页聊天室(二) 前言 接上一次的内容继续完善,今天完成的内容不是很多,只是简单的用户注册登录,内容具体如下 具体内容 这次要加入与数据哭交互的操作,所以首先要建立相关表结构,这里使用 ...

  4. springMVC model传对象数组 jq 获取

    这个问题网上没有什么解答,有两种可能性: 一.我使用的这种方法实在太蠢了正常人都不会去这个搞: 二.我太蠢了.... 以下解决方案 //后台代码如下 public String plant(Model ...

  5. php file_get_contents json_decode 输出为NULL

    解决办法一:不小心在返回的json字符串中返回了BOM头的不可见字符,某些编辑器默认会加上BOM头,如下处理才能正确解析json数据: $info = json_decode(trim($info,c ...

  6. Android开发——程序锁的实现(可用于开发钓鱼登录界面)

    1. 程序锁原理 1.1 实现效果: 在用户打开一个应用时,若此应用是我们业务内的逻辑拦截目标,那就在开启应用之后,弹出一个输入密码的界面,输入密码正确则进入目标应用.若不输入直接按返回键,则直接返回 ...

  7. python--如何在线上环境优雅的修改配置文件?

    1.如何在线上环境优雅的修改配置文件? 原配置文件 #原配置文件 global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 ...

  8. python基础知识--条件判断和循环

    一.输入输出 python怎么来接收用户输入呢,使用input函数,python2中使用raw_input,接收的是一个字符串,输出呢,第一个程序已经写的使用print,代码入下: 1 name=in ...

  9. Codeforces225B - Well-known Numbers

    Portal Description 定义\(k\)-bonacci数列\(\{F_n\}\):\(F_i=0 \ (i<k),F_i=1 \ (i=k),F_i=\sum_{j=i-k}^{i ...

  10. hdu 2167 状态压缩

    /*与1565的解法差不多*/ #include<stdio.h> #include<string.h> int map[16][16]; int dp[2][1<< ...