Skip to content

Instantly share code, notes, and snippets.

@liamcary
Last active August 4, 2025 03:07
Show Gist options
  • Select an option

  • Save liamcary/9fbfcbb04a0308401c5f3caaa458c114 to your computer and use it in GitHub Desktop.

Select an option

Save liamcary/9fbfcbb04a0308401c5f3caaa458c114 to your computer and use it in GitHub Desktop.
Generic ObjectRegistry for Unity to track instances of a type, with Mirror example
// IObjectRegistry.cs
using System;
using System.Collections.Generic;
public interface IObjectRegistry<T>
{
IReadOnlyCollection<T> Instances { get; }
event Action<T> OnInstanceRegistered;
event Action<T> OnInstanceUnregistered;
bool Register(T instance);
bool Unregister(T instance);
}
// ObjectRegistry.cs
using System;
using System.Collections.Generic;
public class ObjectRegistry<T> : IObjectRegistry<T>
{
public IReadOnlyCollection<T> Instances => _instances;
public event Action<T> OnInstanceRegistered;
public event Action<T> OnInstanceUnregistered;
readonly HashSet<T> _instances = new();
public bool Register(T instance)
{
if (_instances.Add(instance)) {
OnInstanceRegistered?.Invoke(instance);
return true;
}
return false;
}
public bool Unregister(T instance)
{
if (_instances.Remove(instance)) {
OnInstanceUnregistered?.Invoke(instance);
return true;
}
return false;
}
}
// Usage example: MonoBehaviour
using UnityEngine;
public class ExampleObject : MonoBehaviour
{
public static ObjectRegistry<ExampleObject> Registry { get; } = new();
void OnEnable()
{
Registry.Register(this);
}
void OnDisable()
{
Registry.Unregister(this);
}
}
// Usage example: Mirror NetworkBehaviour
using Mirror;
public class UserIdentity : NetworkBehaviour
{
public static ObjectRegistry<UserIdentity> Registry { get; } = new();
public string UserId => _userId;
public string Username => _username;
public int Level => _level;
[SyncVar] string _userId;
[SyncVar] string _username;
[SyncVar] int _level;
[Server]
public void Initialize(string userId, string username, int level)
{
_userId = userId;
_username = username;
_level = level;
}
public override void OnStartClient()
{
Registry.Register(this);
}
public override void OnStopClient()
{
Registry.Unregister(this);
}
public override void OnStartServer()
{
Registry.Register(this);
}
public override void OnStopServer()
{
Registry.Unregister(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment