SinglePooledDynamicSpawner.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System.Collections;
  2. using Unity.Netcode;
  3. using UnityEngine;
  4. public class SinglePooledDynamicSpawner : NetworkBehaviour, INetworkPrefabInstanceHandler
  5. {
  6. public GameObject PrefabToSpawn;
  7. public bool SpawnPrefabAutomatically;
  8. private GameObject m_PrefabInstance;
  9. private NetworkObject m_SpawnedNetworkObject;
  10. private void Start()
  11. {
  12. //客户端和服务端,都先实例化物体
  13. m_PrefabInstance = Instantiate(PrefabToSpawn);
  14. m_SpawnedNetworkObject = m_PrefabInstance.GetComponent<NetworkObject>();
  15. m_PrefabInstance.SetActive(false);
  16. }
  17. //延迟2秒后,NetworkObject.Despawn
  18. private IEnumerator DespawnTimer()
  19. {
  20. yield return new WaitForSeconds(2);
  21. m_SpawnedNetworkObject.Despawn();
  22. StartCoroutine(SpawnTimer());
  23. yield break;
  24. }
  25. //延迟2秒手
  26. private IEnumerator SpawnTimer()
  27. {
  28. yield return new WaitForSeconds(2);
  29. SpawnInstance();
  30. yield break;
  31. }
  32. //实现INetworkPrefabInstanceHandler.Instantiate方法,客户端调用
  33. public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
  34. {
  35. m_PrefabInstance.SetActive(true);
  36. m_PrefabInstance.transform.position = transform.position;
  37. m_PrefabInstance.transform.rotation = transform.rotation;
  38. return m_SpawnedNetworkObject;
  39. }
  40. //客户端和服务端
  41. //实现INetworkPrefabInstanceHandler.Destroy
  42. public void Destroy(NetworkObject networkObject)
  43. {
  44. m_PrefabInstance.SetActive(false);
  45. }
  46. public void SpawnInstance()
  47. {
  48. if(!IsServer)
  49. {
  50. return;
  51. }
  52. if(m_PrefabInstance != null && m_SpawnedNetworkObject != null && !m_SpawnedNetworkObject.IsSpawned)
  53. {
  54. m_PrefabInstance.SetActive(true);
  55. m_SpawnedNetworkObject.Spawn();
  56. StartCoroutine(DespawnTimer());
  57. }
  58. }
  59. public override void OnNetworkSpawn()
  60. {
  61. //注册自己
  62. NetworkManager.PrefabHandler.AddHandler(PrefabToSpawn, this);
  63. if(!IsServer || !SpawnPrefabAutomatically)
  64. {
  65. return;
  66. }
  67. if(SpawnPrefabAutomatically)
  68. {
  69. SpawnInstance();
  70. }
  71. }
  72. public override void OnNetworkDespawn()
  73. {
  74. if(m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned)
  75. {
  76. m_SpawnedNetworkObject.Despawn();
  77. }
  78. base.OnNetworkDespawn();
  79. }
  80. public override void OnDestroy()
  81. {
  82. if(m_PrefabInstance != null)
  83. {
  84. NetworkManager.Singleton.PrefabHandler.RemoveHandler(PrefabToSpawn);
  85. Destroy(m_PrefabInstance);
  86. }
  87. base.OnDestroy();
  88. }
  89. }