ZoneHandler.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using UnityEngine;
  2. namespace Mirror.Examples.AdditiveScenes
  3. {
  4. // AdditiveNetworkManager, in OnStartServer, instantiates the prefab only on the server.
  5. // It never exists for clients (other than host client if there is one).
  6. // The prefab has a Sphere Collider with isTrigger = true.
  7. // These OnTrigger events only run on the server and will only send a message to the
  8. // client that entered the Zone to load the subscene assigned to the subscene property.
  9. public class ZoneHandler : MonoBehaviour
  10. {
  11. [Scene]
  12. [Tooltip("Assign the sub-scene to load for this zone")]
  13. public string subScene;
  14. [ServerCallback]
  15. void OnTriggerEnter(Collider other)
  16. {
  17. // ignore collisions with non-Player objects
  18. if (!other.CompareTag("Player")) return;
  19. if (other.TryGetComponent(out NetworkIdentity networkIdentity))
  20. {
  21. SceneMessage message = new SceneMessage { sceneName = subScene, sceneOperation = SceneOperation.LoadAdditive };
  22. networkIdentity.connectionToClient.Send(message);
  23. }
  24. }
  25. [ServerCallback]
  26. void OnTriggerExit(Collider other)
  27. {
  28. // ignore collisions with non-Player objects
  29. if (!other.CompareTag("Player")) return;
  30. if (other.TryGetComponent(out NetworkIdentity networkIdentity))
  31. {
  32. SceneMessage message = new SceneMessage { sceneName = subScene, sceneOperation = SceneOperation.UnloadAdditive };
  33. networkIdentity.connectionToClient.Send(message);
  34. }
  35. }
  36. }
  37. }