79 lines
2.1 KiB
C#
79 lines
2.1 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace MegaKoop.Game.Networking
|
|
{
|
|
[DisallowMultipleComponent]
|
|
public class NetworkIdentity : MonoBehaviour
|
|
{
|
|
private static readonly Dictionary<int, NetworkIdentity> registry = new();
|
|
private static int nextId = 1;
|
|
|
|
[SerializeField] private int networkId;
|
|
[SerializeField] private bool assignOnAwake = true;
|
|
|
|
public int NetworkId => networkId;
|
|
|
|
private void Awake()
|
|
{
|
|
if (assignOnAwake && networkId == 0)
|
|
{
|
|
networkId = nextId++;
|
|
}
|
|
|
|
Register();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (registry.TryGetValue(networkId, out NetworkIdentity existing) && existing == this)
|
|
{
|
|
registry.Remove(networkId);
|
|
}
|
|
}
|
|
|
|
private void Register()
|
|
{
|
|
if (networkId == 0)
|
|
{
|
|
Debug.LogWarning($"[NetworkIdentity] {name} has no network id and won't be tracked.");
|
|
return;
|
|
}
|
|
|
|
if (registry.TryGetValue(networkId, out NetworkIdentity existing) && existing != this)
|
|
{
|
|
Debug.LogWarning($"[NetworkIdentity] Duplicate network id {networkId} detected. Overwriting reference.");
|
|
}
|
|
|
|
registry[networkId] = this;
|
|
}
|
|
|
|
public static bool TryGet(int id, out NetworkIdentity identity) => registry.TryGetValue(id, out identity);
|
|
|
|
/// <summary>
|
|
/// Allows deterministic assignment so IDs match across clients.
|
|
/// </summary>
|
|
public void SetNetworkId(int id)
|
|
{
|
|
if (id == 0)
|
|
{
|
|
Debug.LogWarning("[NetworkIdentity] Cannot assign network id 0.");
|
|
return;
|
|
}
|
|
|
|
if (networkId == id)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (registry.TryGetValue(networkId, out NetworkIdentity existing) && existing == this)
|
|
{
|
|
registry.Remove(networkId);
|
|
}
|
|
|
|
networkId = id;
|
|
Register();
|
|
}
|
|
}
|
|
}
|