Is there an attribute for allowing only a single component to exist in the project?
No. And if that’s a requirement you probably want to rethink your architecture.
If there is no other way; here is a static script to check for duplicate scripts on gameobjects.
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
static class CheckMonoSingleton
{
static bool WarningTriggered;
[InitializeOnLoadMethod]
static void Start()
{
EditorApplication.update += Update;
}
static void Update()
{
if (Application.isPlaying || WarningTriggered) return;
TrackScript<MainWeatherController>();
}
static void TrackScript<T>() where T : Component
{
var data = GameObject.FindObjectsByType<T>(FindObjectsInactive.Include, FindObjectsSortMode.None);
if (data.Length <= 0)
{
Debug.LogWarning("There is no gameobject with " + data);
WarningTriggered = true;
}
else if (data.Length > 1)
{
string location = string.Empty;
for (int i = 0; i < data.Length; i++)
{
location += (i + 1) + " " + data[i].gameObject.name + " ";
}
Debug.LogError("There is more then one gameobject with " + data + " " + location);
WarningTriggered = true;
}
}
}
#endif
This is not the majority of my scripts.
That script is going to kill performance in large scenes.
The number one rule of singleton monobehaviours is they should NEVER be dragged into scenes.
They should initialise themselves when the singleton instance is accessed, either simply constructing themselves, or loading themselves from Resources or Addressables.
I’m using ECS.
Mono Scripts will never be the majority and will never handle a large workload.
Doesn’t really change everything else I said. Singleton monobehaviours should not be dragged into scenes.
Defeats the purpose of them being singleton.
I don’t like mono’s way of creating singletons.
The script was worded singleton in the context of ECS singleton rules. Meaning there must be exactly one component.