75 lines
2.5 KiB
C#
75 lines
2.5 KiB
C#
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<ulong, GameNetworkClient> 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<FixedString32Bytes> mPlayerName = new
|
|
(
|
|
default,
|
|
NetworkVariableReadPermission.Everyone,
|
|
NetworkVariableWritePermission.Owner
|
|
);
|
|
|
|
private readonly NetworkVariable<int> 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<GameNetworkClient>(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);
|
|
}
|
|
}
|