using System.Collections.Generic; using Unity.Netcode; using System.Linq; using Unity.Collections; using UnityEngine; namespace PashaBibko.PenguinChase.Network { public class GameNetworkClient : NetworkBehaviour { public static int LocalClientCount { get; set; } public static string LocalName { get; set; } private static readonly Dictionary sConnectedClients = new(); private static bool sDoneInitialSearch = false; public static GameNetworkClient LocalClient { get; private set; } public static GameNetworkClient[] ConnectedClients => sConnectedClients.Values.ToArray(); public static int ConnectedClientCount => sConnectedClients.Count; private readonly NetworkVariable mPlayerName = new ( default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner ); private readonly NetworkVariable mLocalPlayerCount = new ( 0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner ); public int LocalPlayerCount => mLocalPlayerCount.Value; public string PlayerName => mPlayerName.Value.ToString(); private void Start() { // If it is the local instance registers it as such if (IsOwner) { mLocalPlayerCount.Value = LocalClientCount; mPlayerName.Value = LocalName; LocalClient = this; Debug.Log($"[Game Network Client] has had start called [{LocalName} | {mPlayerName.Value}]"); } // Searches for existing clients if it is the first one to be locally loaded if (!sDoneInitialSearch) { GameNetworkClient[] clients = FindObjectsByType(FindObjectsSortMode.None); foreach (GameNetworkClient client in clients) { ulong clientId = client.OwnerClientId; sConnectedClients.Add(clientId, this); } sDoneInitialSearch = true; } // Else adds it to the global list of clients else { sConnectedClients.Add(OwnerClientId, this); } } public override void OnDestroy() => sConnectedClients.Remove(OwnerClientId); } }