48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
using PashaBibko.PenguinChase.Extensions;
|
|
using Unity.Netcode;
|
|
using UnityEngine;
|
|
|
|
namespace PashaBibko.PenguinChase.Network
|
|
{
|
|
public class ConnectionManager : MonoBehaviour
|
|
{
|
|
private static ConnectionManager sInstance;
|
|
|
|
[SerializeField] private GameObject PrefabForEachClient;
|
|
public static GameObject ClientPrefab => sInstance?.PrefabForEachClient;
|
|
|
|
private void Awake()
|
|
{
|
|
// Stops overlapping instances
|
|
if (sInstance is not null)
|
|
{
|
|
Debug.LogError($"Multiple of [{nameof(ConnectionManager)}] cannot exist.");
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
|
|
sInstance = this;
|
|
}
|
|
|
|
public static void CreateNetworkConnectionManager()
|
|
{
|
|
NetworkManager.Singleton.OnClientConnectedCallback += OnClientJoin;
|
|
OnClientJoin(0); // Has to be manually called for local client
|
|
}
|
|
|
|
public static void DestroyNetworkConnectionManager()
|
|
{
|
|
NetworkManager.Singleton.OnClientConnectedCallback -= OnClientJoin;
|
|
sInstance.DestroyAllChildren();
|
|
}
|
|
|
|
private static void OnClientJoin(ulong id)
|
|
{
|
|
GameObject client = Instantiate(ClientPrefab);
|
|
DontDestroyOnLoad(client);
|
|
|
|
NetworkObject networkObject = client.GetComponent<NetworkObject>();
|
|
networkObject.SpawnAsPlayerObject(id);
|
|
}
|
|
}
|
|
} |