CCUNetworkManager.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using UnityEngine;
  2. namespace Mirror.Examples.CCU
  3. {
  4. public class CCUNetworkManager : NetworkManager
  5. {
  6. [Header("Spawns")]
  7. public int spawnAmount = 10_000;
  8. public float interleave = 1;
  9. public GameObject spawnPrefab;
  10. // player spawn positions should be spread across the world.
  11. // not all at one place.
  12. // but _some_ at the same place.
  13. // => deterministic random is ideal
  14. [Range(0, 1)] public float spawnPositionRatio = 0.01f;
  15. System.Random random = new System.Random(42);
  16. void SpawnAll()
  17. {
  18. // clear previous player spawn positions in case we start twice
  19. foreach (Transform position in startPositions)
  20. Destroy(position.gameObject);
  21. startPositions.Clear();
  22. // calculate sqrt so we can spawn N * N = Amount
  23. float sqrt = Mathf.Sqrt(spawnAmount);
  24. // calculate spawn xz start positions
  25. // based on spawnAmount * distance
  26. float offset = -sqrt / 2 * interleave;
  27. // spawn exactly the amount, not one more.
  28. int spawned = 0;
  29. for (int spawnX = 0; spawnX < sqrt; ++spawnX)
  30. {
  31. for (int spawnZ = 0; spawnZ < sqrt; ++spawnZ)
  32. {
  33. // spawn exactly the amount, not any more
  34. // (our sqrt method isn't 100% precise)
  35. if (spawned < spawnAmount)
  36. {
  37. // spawn & position
  38. GameObject go = Instantiate(spawnPrefab);
  39. float x = offset + spawnX * interleave;
  40. float z = offset + spawnZ * interleave;
  41. Vector3 position = new Vector3(x, 0, z);
  42. go.transform.position = position;
  43. // spawn
  44. NetworkServer.Spawn(go);
  45. ++spawned;
  46. // add random spawn position for players.
  47. // don't have them all in the same place.
  48. if (random.NextDouble() <= spawnPositionRatio)
  49. {
  50. GameObject spawnGO = new GameObject("Spawn");
  51. spawnGO.transform.position = position;
  52. spawnGO.AddComponent<NetworkStartPosition>();
  53. }
  54. }
  55. }
  56. }
  57. }
  58. // overwrite random spawn position selection:
  59. // - needs to be deterministic so every CCU test results in the same
  60. // - needs to be random so not only are the spawn positions spread out
  61. // randomly, we also have a random amount of players per spawn position
  62. public override Transform GetStartPosition()
  63. {
  64. // first remove any dead transforms
  65. startPositions.RemoveAll(t => t == null);
  66. if (startPositions.Count == 0)
  67. return null;
  68. // pick a random one
  69. int index = random.Next(0, startPositions.Count); // DETERMINISTIC
  70. return startPositions[index];
  71. }
  72. public override void OnStartServer()
  73. {
  74. base.OnStartServer();
  75. SpawnAll();
  76. }
  77. }
  78. }