ZoneHandler.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using UnityEngine;
  2. namespace Mirror.Examples.Additive
  3. {
  4. // This script is attached to a prefab called Zone that is on the Player layer
  5. // AdditiveNetworkManager, in OnStartServer, instantiates the prefab only on the server.
  6. // It never exists for clients (other than host client if there is one).
  7. // The prefab has a Sphere Collider with isTrigger = true.
  8. // These OnTrigger events only run on the server and will only send a message to the
  9. // client that entered the Zone to load the subscene assigned to the subscene property.
  10. public class ZoneHandler : MonoBehaviour
  11. {
  12. [Scene]
  13. [Tooltip("Assign the sub-scene to load for this zone")]
  14. public string subScene;
  15. [ServerCallback]
  16. void OnTriggerEnter(Collider other)
  17. {
  18. // Debug.Log($"Loading {subScene}");
  19. NetworkIdentity networkIdentity = other.gameObject.GetComponent<NetworkIdentity>();
  20. SceneMessage message = new SceneMessage{ sceneName = subScene, sceneOperation = SceneOperation.LoadAdditive };
  21. networkIdentity.connectionToClient.Send(message);
  22. }
  23. [ServerCallback]
  24. void OnTriggerExit(Collider other)
  25. {
  26. // Debug.Log($"Unloading {subScene}");
  27. NetworkIdentity networkIdentity = other.gameObject.GetComponent<NetworkIdentity>();
  28. SceneMessage message = new SceneMessage{ sceneName = subScene, sceneOperation = SceneOperation.UnloadAdditive };
  29. networkIdentity.connectionToClient.Send(message);
  30. }
  31. }
  32. }