AdditiveNetworkManager.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.SceneManagement;
  4. namespace Mirror.Examples.AdditiveScenes
  5. {
  6. [AddComponentMenu("")]
  7. public class AdditiveNetworkManager : NetworkManager
  8. {
  9. [Tooltip("Trigger Zone Prefab")]
  10. public GameObject Zone;
  11. [Scene]
  12. [Tooltip("Add all sub-scenes to this list")]
  13. public string[] subScenes;
  14. public static new AdditiveNetworkManager singleton { get; private set; }
  15. /// <summary>
  16. /// Runs on both Server and Client
  17. /// Networking is NOT initialized when this fires
  18. /// </summary>
  19. public override void Awake()
  20. {
  21. base.Awake();
  22. singleton = this;
  23. }
  24. public override void OnStartServer()
  25. {
  26. base.OnStartServer();
  27. // load all subscenes on the server only
  28. StartCoroutine(LoadSubScenes());
  29. // Instantiate Zone Handler on server only
  30. Instantiate(Zone);
  31. }
  32. public override void OnStopServer()
  33. {
  34. StartCoroutine(UnloadScenes());
  35. }
  36. public override void OnStopClient()
  37. {
  38. if (mode == NetworkManagerMode.Offline)
  39. StartCoroutine(UnloadScenes());
  40. }
  41. IEnumerator LoadSubScenes()
  42. {
  43. Debug.Log("Loading Scenes");
  44. foreach (string sceneName in subScenes)
  45. yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
  46. }
  47. IEnumerator UnloadScenes()
  48. {
  49. Debug.Log("Unloading Subscenes");
  50. foreach (string sceneName in subScenes)
  51. if (SceneManager.GetSceneByName(sceneName).IsValid() || SceneManager.GetSceneByPath(sceneName).IsValid())
  52. yield return SceneManager.UnloadSceneAsync(sceneName);
  53. yield return Resources.UnloadUnusedAssets();
  54. }
  55. }
  56. }