comparison of the Event Bus, Mediator, and Singleton design patterns in C# with Unity
majd abbassi
?? Unity Game Developer | ?? Fullstack Web Developer (Next.js, ASP.NET) | ?? Unreal Engine (Blueprint)
Event Bus:
public class EventBusExample : MonoBehaviour
{
public UnityEvent<int> OnValueChanged;
private int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
OnValueChanged.Invoke(value); // Publish event
}
}
}
Mediator:
领英推荐
public class MediatorExample : ScriptableObject
{
public void PerformAction(GameObject obj, string action)
{
switch (action)
{
case "Move":
obj.transform.Translate(Vector3.forward);
break;
case "Shoot":
obj.GetComponent<Weapon>().Shoot();
break;
}
}
}
Singleton:
public class SettingsSingleton : MonoBehaviour
{
private static SettingsSingleton _instance;
public static SettingsSingleton Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<SettingsSingleton>();
if (_instance == null)
{
GameObject obj = new GameObject("SettingsSingleton");
_instance = obj.AddComponent<SettingsSingleton>();
}
}
return _instance;
}
}
public float MasterVolume = 1f;
public float MusicVolume = 0.8f;
public float SfxVolume = 0.9f;
}
Conclusion
These design patterns offer different approaches to managing communication and state in your Unity projects. The Event Bus decouples publishers and subscribers, the Mediator centralizes coordination, and the Singleton ensures global access to a single instance. Choosing the right pattern depends on the specific requirements of your application.