94 lines
2.9 KiB
C#
94 lines
2.9 KiB
C#
using UnityEngine;
|
|
|
|
namespace MegaKoop.Game.Networking
|
|
{
|
|
[DisallowMultipleComponent]
|
|
public class NetworkIdentity : MonoBehaviour
|
|
{
|
|
[SerializeField] private int networkId;
|
|
[SerializeField] private bool assignOnAwake = false; // Changed default to false - IDs should be assigned deterministically
|
|
|
|
public int NetworkId => networkId;
|
|
|
|
private void Awake()
|
|
{
|
|
// Note: Auto-increment removed in favor of deterministic ID generation
|
|
// IDs should be assigned via SetNetworkId() before or during Awake
|
|
if (assignOnAwake && networkId == 0)
|
|
{
|
|
Debug.LogWarning($"[NetworkIdentity] {name} has assignOnAwake=true but no ID assigned. " +
|
|
"Use DeterministicIdGenerator or manually call SetNetworkId().");
|
|
}
|
|
|
|
Register();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
NetworkIdRegistry.Unregister(networkId);
|
|
}
|
|
|
|
private void Register()
|
|
{
|
|
if (networkId == 0)
|
|
{
|
|
Debug.LogWarning($"[NetworkIdentity] {name} has no network id and won't be tracked.");
|
|
return;
|
|
}
|
|
|
|
if (!NetworkIdRegistry.TryRegister(this))
|
|
{
|
|
Debug.LogError($"[NetworkIdentity] Failed to register {name} with ID {networkId}. " +
|
|
"This object will not be synchronized correctly!");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieves a NetworkIdentity by its ID using the centralized registry.
|
|
/// </summary>
|
|
public static bool TryGet(int id, out NetworkIdentity identity)
|
|
{
|
|
identity = NetworkIdRegistry.GetById(id);
|
|
return identity != null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Allows deterministic assignment so IDs match across clients.
|
|
/// This should be called before the object is used in network communication.
|
|
/// </summary>
|
|
public void SetNetworkId(int id)
|
|
{
|
|
if (id == 0)
|
|
{
|
|
Debug.LogError("[NetworkIdentity] Cannot assign network id 0.");
|
|
return;
|
|
}
|
|
|
|
if (networkId == id)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Unregister old ID if it was registered
|
|
if (networkId != 0)
|
|
{
|
|
NetworkIdRegistry.Unregister(networkId);
|
|
}
|
|
|
|
networkId = id;
|
|
|
|
// Register with new ID
|
|
if (!NetworkIdRegistry.TryRegister(this))
|
|
{
|
|
Debug.LogError($"[NetworkIdentity] Failed to set network ID {id} for {name}. " +
|
|
"ID may already be in use!");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the current network ID without triggering registration.
|
|
/// </summary>
|
|
public int GetNetworkId() => networkId;
|
|
}
|
|
}
|