123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- using System.Collections;
- using Unity.Netcode;
- using UnityEngine;
- public class SinglePooledDynamicSpawner : NetworkBehaviour, INetworkPrefabInstanceHandler
- {
- public GameObject PrefabToSpawn;
- public bool SpawnPrefabAutomatically;
- private GameObject m_PrefabInstance;
- private NetworkObject m_SpawnedNetworkObject;
- private void Start()
- {
- //客户端和服务端,都先实例化物体
- m_PrefabInstance = Instantiate(PrefabToSpawn);
- m_SpawnedNetworkObject = m_PrefabInstance.GetComponent<NetworkObject>();
- m_PrefabInstance.SetActive(false);
- }
- //延迟2秒后,NetworkObject.Despawn
- private IEnumerator DespawnTimer()
- {
- yield return new WaitForSeconds(2);
- m_SpawnedNetworkObject.Despawn();
- StartCoroutine(SpawnTimer());
- yield break;
- }
- //延迟2秒手
- private IEnumerator SpawnTimer()
- {
- yield return new WaitForSeconds(2);
- SpawnInstance();
- yield break;
- }
- //实现INetworkPrefabInstanceHandler.Instantiate方法,客户端调用
- public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
- {
- m_PrefabInstance.SetActive(true);
- m_PrefabInstance.transform.position = transform.position;
- m_PrefabInstance.transform.rotation = transform.rotation;
- return m_SpawnedNetworkObject;
- }
- //客户端和服务端
- //实现INetworkPrefabInstanceHandler.Destroy
- public void Destroy(NetworkObject networkObject)
- {
- m_PrefabInstance.SetActive(false);
- }
- public void SpawnInstance()
- {
- if(!IsServer)
- {
- return;
- }
- if(m_PrefabInstance != null && m_SpawnedNetworkObject != null && !m_SpawnedNetworkObject.IsSpawned)
- {
- m_PrefabInstance.SetActive(true);
- m_SpawnedNetworkObject.Spawn();
- StartCoroutine(DespawnTimer());
- }
- }
- public override void OnNetworkSpawn()
- {
- //注册自己
- NetworkManager.PrefabHandler.AddHandler(PrefabToSpawn, this);
- if(!IsServer || !SpawnPrefabAutomatically)
- {
- return;
- }
- if(SpawnPrefabAutomatically)
- {
- SpawnInstance();
- }
- }
- public override void OnNetworkDespawn()
- {
- if(m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned)
- {
- m_SpawnedNetworkObject.Despawn();
- }
- base.OnNetworkDespawn();
- }
- public override void OnDestroy()
- {
- if(m_PrefabInstance != null)
- {
- NetworkManager.Singleton.PrefabHandler.RemoveHandler(PrefabToSpawn);
- Destroy(m_PrefabInstance);
- }
- base.OnDestroy();
- }
- }
|