12345678910111213141516171819202122232425262728293031323334353637383940 |
- using Unity.Netcode;
- using UnityEngine;
- //非对象池的动态对象生成
- public class NonPooledDynamicSpawner : NetworkBehaviour
- {
- public GameObject PrefabToSpawn;
- public bool DestroyWithSpawner;
- private GameObject m_PrefabInstance;
- private NetworkObject m_SpawnedNetworkObject;
- public override void OnNetworkSpawn()
- {
- //只有服务端可以生成
- enabled = IsServer;
- if(!enabled || PrefabToSpawn == null)
- {
- return;
- }
- //生成prefab
- m_PrefabInstance = Instantiate(PrefabToSpawn);
- m_PrefabInstance.transform.position = transform.position;
- m_PrefabInstance.transform.rotation = transform.rotation;
- m_SpawnedNetworkObject = m_PrefabInstance.GetComponent<NetworkObject>();
- m_SpawnedNetworkObject.Spawn();
- }
- public override void OnNetworkDespawn()
- {
- if(IsServer && DestroyWithSpawner && m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned)
- {
- m_SpawnedNetworkObject.Despawn();
- }
- base.OnNetworkDespawn();
- }
- }
|