Skip to content

Commit

Permalink
Added support for singletons that might exist in editor context
Browse files Browse the repository at this point in the history
  • Loading branch information
sliptrixx committed Aug 1, 2023
1 parent 4f88378 commit e42de03
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
41 changes: 40 additions & 1 deletion Scripts/Core/Singleton.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static T Instance
// Used to create a new instance of the singleton
private static T RequestNewInstance()
{
T[] items = FindObjectsOfType<T>();
T[] items = GetAllObjects();
if (items.Length == 0)
{
// Using the reflection system, look if CreateNewInstance is being overriden
Expand Down Expand Up @@ -71,6 +71,45 @@ protected static T CreateNewInstance()
return obj.AddComponent<T>();
}

// Summary: Get all components of type T in the scene
// Remarks: This is an editor friendly version of FindObjectsOfType
// that works on singletons that exist on an editor context.
// The function is more expensive in editor context, however
// remains cheap in regular playmode.
protected static T[] GetAllObjects()
{
#if UNITY_EDITOR

// when the editor is in play mode, FindObjectsOfType will work
if (Application.isPlaying)
{
return FindObjectsOfType<T>();
}

// the editor is not in playmode, so in the editor context
// this container will store all objects found of type T in the scene
List<T> singletons = new List<T>();

GameObject[] rootObjects = SceneManager.GetActiveScene().GetRootGameObjects();
foreach (var rootObject in rootObjects)
{
var comps = rootObject.GetComponentsInChildren<T>();
foreach (var comp in comps)
{
singletons.Add(comp);
}
}

// convert the list to an array, as that's the return type expected
return singletons.ToArray();

#else

return FindObjectsOfType<T>();

#endif
}

// when the singleton object gets destroyed, we make sure that the
// static singleton reference is cleared
protected virtual void OnDestroy()
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "com.hibzz.singletons",
"version": "1.2.0",
"version": "1.3.0",
"displayName": "hibzz.singletons",
"description": "A library of singletons for Unity",
"author": {
Expand Down

0 comments on commit e42de03

Please sign in to comment.