Characters
This commit is contained in:
53
Game/Scripts/Networking/NetworkIdentity.cs
Normal file
53
Game/Scripts/Networking/NetworkIdentity.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user