-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathNetworkPrefabPool.cs
More file actions
636 lines (562 loc) · 21.9 KB
/
NetworkPrefabPool.cs
File metadata and controls
636 lines (562 loc) · 21.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace TestProject.ManualTests
{
public class NetworkPrefabPool : NetworkBehaviour, INetworkPrefabInstanceHandler
{
[Header("General Settings")]
public bool AutoSpawnEnable = true;
public float InitialSpawnDelay;
public int SpawnsPerSecond;
public int PoolSize;
public float ObjectSpeed = 10.0f;
public bool DontDestroy;
public bool LabelEnabled = true;
public int MaximumSpawnCount = 1000;
public Toggle HalfFloat;
public Toggle QuatSynch;
public Toggle QuatComp;
[Header("Prefab Instance Handling")]
[Tooltip("When enabled, this will utilize the NetworkPrefabHandler to register a custom INetworkPrefabInstanceHandler")]
public bool EnableHandler;
[Tooltip("When enabled, this will register a custom INetworkPrefabInstanceHandler using a NetworkObject reference")]
public bool RegisterUsingNetworkObject;
[Tooltip("What is going to be spawned on the server side from the pool.")]
public GameObject ServerObjectToPool;
[Tooltip("What is going to be spawned on the client side from the ")]
public GameObject ClientObjectToPool;
[Header("Component Connections")]
public SwitchSceneHandler SwitchScene;
public Slider SpawnSlider;
public Text SpawnSliderValueText;
private bool m_IsSpawningObjects;
private float m_EntitiesPerFrame;
private float m_DelaySpawning;
private GameObject m_ObjectToSpawn;
private List<GameObject> m_ObjectPool;
private static GameObject s_Instance;
/// <summary>
/// Called when enabled, if already connected we register any custom prefab spawn handler here
/// </summary>
private void OnEnable()
{
m_IsExitingScene = false;
if (DontDestroy)
{
if (s_Instance != null && s_Instance != this)
{
var instancePool = s_Instance.GetComponent<NetworkPrefabPool>();
if (instancePool.m_ObjectPool != null)
{
instancePool.MoveBackToCurrentlyActiveScene();
instancePool.m_ObjectPool.Clear();
m_ObjectPool = new List<GameObject>(instancePool.m_ObjectPool);
}
Destroy(s_Instance);
s_Instance = null;
}
if (s_Instance == null)
{
s_Instance = gameObject;
DontDestroyOnLoad(gameObject);
}
}
SpawnSlider?.gameObject.SetActive(false);
}
private bool m_IsExitingScene;
public void OnExitingScene(bool destroyObjects)
{
m_IsExitingScene = true;
if (DontDestroy)
{
if (destroyObjects)
{
OnDestroyObjectPool();
SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene());
s_Instance = null;
}
else
{
MovePoolObjectsToDontDestroyOnLoad();
}
}
}
private void MovePoolObjectsToDontDestroyOnLoad()
{
foreach (var obj in m_ObjectPool)
{
obj.GetComponent<NetworkObject>().AutoObjectParentSync = false;
obj.transform.parent = gameObject.transform;
}
}
private void MoveBackToCurrentlyActiveScene()
{
var activeScene = SceneManager.GetActiveScene();
foreach (var obj in m_ObjectPool)
{
obj.transform.parent = null;
obj.GetComponent<NetworkObject>().AutoObjectParentSync = true;
SceneManager.MoveGameObjectToScene(obj, activeScene);
var genericBehaviour = obj.GetComponent<GenericNetworkObjectBehaviour>();
genericBehaviour.Reset();
}
}
private bool m_IsQuitting;
private void OnApplicationQuit()
{
m_IsQuitting = true;
if (DontDestroy)
{
OnDestroyObjectPool();
}
}
private void OnDisable()
{
if (!m_IsQuitting)
{
DeregisterCustomPrefabHandler();
}
}
/// <summary>
/// Handles registering the custom prefab handler
/// </summary>
private void RegisterCustomPrefabHandler()
{
// Register the custom spawn handler?
if (EnableHandler)
{
if (NetworkManager && NetworkManager.PrefabHandler != null)
{
if (RegisterUsingNetworkObject)
{
NetworkManager.PrefabHandler.AddHandler(ServerObjectToPool.GetComponent<NetworkObject>(), this);
}
else
{
NetworkManager.PrefabHandler.AddHandler(ServerObjectToPool, this);
}
}
else if (!IsServer)
{
Debug.LogWarning($"Failed to register custom spawn handler and {nameof(EnableHandler)} is set to true!");
}
}
}
private void DeregisterCustomPrefabHandler()
{
// Register the custom spawn handler?
if (EnableHandler && NetworkManager && NetworkManager.PrefabHandler != null)
{
NetworkManager.PrefabHandler.RemoveHandler(ServerObjectToPool);
if (IsClient && m_ObjectToSpawn != null)
{
NetworkManager.PrefabHandler.RemoveHandler(m_ObjectToSpawn);
}
}
}
private void OnSceneEvent(SceneEvent sceneEvent)
{
switch (sceneEvent.SceneEventType)
{
case SceneEventType.Unload:
{
if (sceneEvent.LoadSceneMode == LoadSceneMode.Single && (gameObject.scene.name == sceneEvent.SceneName))
{
OnDestroyObjectPool();
}
break;
}
}
}
/// <summary>
/// Destroys the NetworkObject pool
/// </summary>
private void OnDestroyObjectPool()
{
if (NetworkObject != null && NetworkManager != null)
{
if (IsServer)
{
StopCoroutine(SpawnObjects());
}
// De-register the custom prefab handler
DeregisterCustomPrefabHandler();
CleanNetworkObjects();
if (NetworkManager != null && NetworkManager.SceneManager != null)
{
NetworkManager.SceneManager.OnSceneEvent -= OnSceneEvent;
}
if (DontDestroy)
{
PostNetworkObjectCleanup();
}
}
}
private IEnumerator PostNetworkObjectCleanup()
{
yield return new WaitUntil(() => !NetworkManager.Singleton.IsListening);
yield return new WaitForSeconds(0.5f);
OnNetworkDespawn();
}
public override void OnNetworkDespawn()
{
DeregisterCustomPrefabHandler();
if (NetworkManager != null)
{
NetworkManager.SceneManager.OnSceneEvent -= OnSceneEvent;
}
foreach (var obj in m_ObjectPool)
{
var networkObject = obj.GetComponent<NetworkObject>();
var genericBehaviour = obj.GetComponent<GenericNetworkObjectBehaviour>();
if (networkObject.IsSpawned)
{
Debug.Log($"{networkObject.name} is still considered spawned!");
}
}
}
private void CleanNetworkObjects()
{
if (m_ObjectPool != null)
{
foreach (var obj in m_ObjectPool)
{
if (obj != null)
{
var networkObject = obj.GetComponent<NetworkObject>();
var genericBehaviour = obj.GetComponent<GenericNetworkObjectBehaviour>();
if (genericBehaviour != null)
{
genericBehaviour.IsRegisteredPoolObject = false;
genericBehaviour.IsRemovedFromPool = true;
if (IsServer)
{
if (networkObject.IsSpawned)
{
networkObject.Despawn();
}
else if (!DontDestroy)
{
DestroyImmediate(obj);
}
}
else //Client
{
if (!DontDestroy && !networkObject.IsSpawned)
{
DestroyImmediate(obj);
}
}
}
}
}
if (!DontDestroy)
{
m_ObjectPool.Clear();
}
}
}
private void SetGlobalTransformPropertiesUI(bool isVisible)
{
HalfFloat?.gameObject.SetActive(isVisible);
QuatComp?.gameObject.SetActive(isVisible);
QuatSynch?.gameObject.SetActive(isVisible);
}
private void Awake()
{
SetGlobalTransformPropertiesUI(false);
}
// Start is called before the first frame update
private void Start()
{
if (SpawnSliderValueText != null)
{
SpawnSliderValueText.text = SpawnsPerSecond.ToString();
}
m_LabelEnabled = LabelEnabled;
NetworkObjectLabel.GlobalVisibility = m_LabelEnabled;
if (HalfFloat != null)
{
m_UseHalfFloatPrecision = HalfFloat.isOn;
}
if (QuatSynch != null)
{
m_QuaternionSynchronization = QuatSynch.isOn;
}
if (QuatComp != null)
{
m_CompressQuaternions = QuatComp.isOn;
}
}
private bool m_LabelEnabled;
private bool m_UseHalfFloatPrecision;
private bool m_CompressQuaternions;
private bool m_QuaternionSynchronization;
[ClientRpc]
private void ShowHideObjectIdLabelClientRpc(bool isVisible)
{
m_LabelEnabled = isVisible;
NetworkObjectLabel.GlobalVisibility = m_LabelEnabled;
#if UNITY_2023_1_OR_NEWER
var labels = FindObjectsByType<NetworkObjectLabel>(FindObjectsSortMode.InstanceID);
#else
var labels = FindObjectsOfType<NetworkObjectLabel>();
#endif
foreach (var label in labels)
{
label.SetLabelVisibility(isVisible);
}
}
/// <summary>
/// Override NetworkBehaviour.NetworkStart
/// </summary>
public override void OnNetworkSpawn()
{
NetworkManager.SceneManager.OnSceneEvent += OnSceneEvent;
InitializeObjectPool();
if (IsServer)
{
if (isActiveAndEnabled)
{
m_DelaySpawning = Time.realtimeSinceStartup + InitialSpawnDelay;
StartSpawningBoxes();
//Make sure our slider reflects the current spawn rate
UpdateSpawnsPerSecond();
}
SetGlobalTransformPropertiesUI(true);
}
}
/// <summary>
/// Determines which object is going to be spawned and then
/// initializes the object pool based on
/// </summary>
public void InitializeObjectPool()
{
// Base construction and registration of the custom prefab handler.
RegisterCustomPrefabHandler();
// Default to the server side object
m_ObjectToSpawn = ServerObjectToPool;
// Host and Client need to do an extra step
if (IsClient)
{
if (EnableHandler && ClientObjectToPool != null)
{
m_ObjectToSpawn = NetworkManager.GetNetworkPrefabOverride(ClientObjectToPool);
}
else
{
m_ObjectToSpawn = NetworkManager.GetNetworkPrefabOverride(m_ObjectToSpawn);
}
// Since the host should spawn the override, we need to register the host to link it to the originally registered ServerObjectToPool
if (IsHost && EnableHandler && ServerObjectToPool != m_ObjectToSpawn)
{
// While this seems redundant, we could theoretically have several objects that we could potentially be spawning
NetworkManager.PrefabHandler.RegisterHostGlobalObjectIdHashValues(ServerObjectToPool, new List<GameObject>() { m_ObjectToSpawn });
}
}
if ((EnableHandler || IsServer) && m_ObjectPool == null)
{
m_ObjectPool = new List<GameObject>(PoolSize);
for (int i = 0; i < PoolSize; i++)
{
var gameObject = AddNewInstance();
gameObject.SetActive(false);
}
}
}
/// <summary>
/// Gets an object from the pool
/// </summary>
/// <returns></returns>
public GameObject GetObject()
{
if (m_ObjectPool != null)
{
foreach (var obj in m_ObjectPool)
{
if (obj != null && !obj.activeInHierarchy)
{
obj.SetActive(true);
return obj;
}
}
var newObj = AddNewInstance();
return newObj;
}
return null;
}
/// <summary>
/// Add a new instance to the object pool
/// </summary>
/// <returns>new instance of the m_ObjectToSpawn prefab</returns>
private GameObject AddNewInstance()
{
var obj = Instantiate(m_ObjectToSpawn);
var genericNetworkObjectBehaviour = obj.GetComponent<GenericNetworkObjectBehaviour>();
genericNetworkObjectBehaviour.HasHandler = EnableHandler;
genericNetworkObjectBehaviour.IsRegisteredPoolObject = true;
var networkObjectLabel = obj.GetComponentInChildren<NetworkObjectLabel>();
networkObjectLabel?.SetLabelVisibility(LabelEnabled);
ApplyPrecisionAdjustments(obj);
m_ObjectPool.Add(obj);
return m_ObjectPool[m_ObjectPool.Count - 1];
}
/// <summary>
/// Starts spawning
/// </summary>
private void StartSpawningBoxes()
{
if (NetworkManager.IsHost && SpawnSlider != null)
{
SpawnSlider.gameObject.SetActive(true);
}
if (SpawnsPerSecond > 0)
{
StartCoroutine(SpawnObjects());
}
}
/// <summary>
/// Checks to determine if we need to update our spawns per second calculations
/// </summary>
public void UpdateSpawnsPerSecond()
{
if (SpawnSlider != null)
{
SpawnsPerSecond = (int)SpawnSlider.value;
SpawnSliderValueText.text = SpawnsPerSecond.ToString();
// Handle case where the initial value is set to zero and so coroutine needs to be started
if (SpawnsPerSecond > 0 && !m_IsSpawningObjects)
{
StartSpawningBoxes();
}
else //Handle case where spawning coroutine is running but we set our spawn rate to zero
if (SpawnsPerSecond == 0 && m_IsSpawningObjects)
{
m_IsSpawningObjects = false;
StopCoroutine(SpawnObjects());
}
}
}
private void ApplyPrecisionAdjustments(GameObject gameObject)
{
var networkTransform = gameObject.GetComponent<Unity.Netcode.Components.NetworkTransform>();
if (networkTransform != null)
{
networkTransform.UseQuaternionSynchronization = m_QuaternionSynchronization;
networkTransform.UseHalfFloatPrecision = m_UseHalfFloatPrecision;
networkTransform.UseQuaternionCompression = m_CompressQuaternions;
}
}
private void AdjustPrecision()
{
foreach (var spawnObject in m_ObjectPool)
{
ApplyPrecisionAdjustments(spawnObject);
}
}
private void CheckPropertyChanges()
{
if (m_LabelEnabled != LabelEnabled)
{
m_LabelEnabled = LabelEnabled;
NetworkObjectLabel.GlobalVisibility = m_LabelEnabled;
ShowHideObjectIdLabelClientRpc(m_LabelEnabled);
}
if ((HalfFloat != null && m_UseHalfFloatPrecision != HalfFloat.isOn) || (QuatComp != null && m_CompressQuaternions != QuatComp.isOn)
|| (QuatSynch != null) && m_QuaternionSynchronization != QuatSynch.isOn)
{
m_UseHalfFloatPrecision = HalfFloat.isOn;
m_CompressQuaternions = QuatComp.isOn;
m_QuaternionSynchronization = QuatSynch.isOn;
AdjustPrecision();
}
}
/// <summary>
/// Coroutine to spawn boxes
/// </summary>
/// <returns></returns>
private IEnumerator SpawnObjects()
{
//Exit if we are a client or we happen to not have a NetworkManager
if (NetworkManager == null || (NetworkManager.IsClient && !NetworkManager.IsHost && !NetworkManager.IsServer))
{
yield return null;
}
if (m_DelaySpawning > Time.realtimeSinceStartup)
{
yield return new WaitForSeconds(m_DelaySpawning - Time.realtimeSinceStartup);
}
m_IsSpawningObjects = true;
while (m_IsSpawningObjects && !m_IsExitingScene)
{
//Start spawning if auto spawn is enabled
if (AutoSpawnEnable)
{
float entitySpawnUpdateRate = 1.0f;
CheckPropertyChanges();
if (SpawnsPerSecond > 0)
{
entitySpawnUpdateRate = 1.0f / Mathf.Min(SpawnsPerSecond, 60.0f);
//While not 100% accurate, this basically allows for higher entities per second generation
m_EntitiesPerFrame = SpawnsPerSecond * entitySpawnUpdateRate;
int entitityCountPerFrame = Mathf.RoundToInt(m_EntitiesPerFrame);
//Spawn (n) entities then wait for 1/60th of a second and repeat
for (int i = 0; i < entitityCountPerFrame; i++)
{
if (NetworkManager.SpawnManager.SpawnedObjectsList.Count >= MaximumSpawnCount)
{
break;
}
GameObject go = GetObject();
if (go != null)
{
go.transform.position = transform.position;
float ang = Random.Range(0.0f, 2 * Mathf.PI);
go.GetComponent<GenericNetworkObjectBehaviour>().SetDirectionAndVelocity(new Vector3(Mathf.Cos(ang), 0, Mathf.Sin(ang)), ObjectSpeed);
var no = go.GetComponent<NetworkObject>();
if (!no.IsSpawned)
{
no.Spawn(true);
}
}
}
}
yield return new WaitForSeconds(entitySpawnUpdateRate);
}
else //Just hang out until it is enabled
{
yield return new WaitForSeconds(1.0f);
}
}
}
public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
{
var obj = GetObject();
if (obj != null)
{
obj.transform.position = position;
obj.transform.rotation = rotation;
return obj.GetComponent<NetworkObject>();
}
return null;
}
public void Destroy(NetworkObject networkObject)
{
var genericBehaviour = networkObject.gameObject.GetComponent<GenericNetworkObjectBehaviour>();
if (genericBehaviour.IsRegisteredPoolObject)
{
networkObject.transform.position = transform.position;
networkObject.transform.rotation = transform.rotation;
networkObject.gameObject.SetActive(false);
}
else
{
Destroy(networkObject.gameObject);
}
}
}
}