NonPooledDynamicSpawner.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Unity.Netcode;
  2. using UnityEngine;
  3. //非对象池的动态对象生成
  4. public class NonPooledDynamicSpawner : NetworkBehaviour
  5. {
  6. public GameObject PrefabToSpawn;
  7. public bool DestroyWithSpawner;
  8. private GameObject m_PrefabInstance;
  9. private NetworkObject m_SpawnedNetworkObject;
  10. public override void OnNetworkSpawn()
  11. {
  12. //只有服务端可以生成
  13. enabled = IsServer;
  14. if(!enabled || PrefabToSpawn == null)
  15. {
  16. return;
  17. }
  18. //生成prefab
  19. m_PrefabInstance = Instantiate(PrefabToSpawn);
  20. m_PrefabInstance.transform.position = transform.position;
  21. m_PrefabInstance.transform.rotation = transform.rotation;
  22. m_SpawnedNetworkObject = m_PrefabInstance.GetComponent<NetworkObject>();
  23. m_SpawnedNetworkObject.Spawn();
  24. }
  25. public override void OnNetworkDespawn()
  26. {
  27. if(IsServer && DestroyWithSpawner && m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned)
  28. {
  29. m_SpawnedNetworkObject.Despawn();
  30. }
  31. base.OnNetworkDespawn();
  32. }
  33. }