Great job, could even be extended to support editor mode
aybe opened this issue · 3 comments
aybe commented
Thanks for the code, I believe it could be further enhanced to support editor mode, like the following:
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using UnityEngine;
namespace Z
{
[PublicAPI]
[ExecuteAlways]
public abstract class Singleton<T> : MonoBehaviour where T : Component
{
private static T _instance;
public static T Instance
{
get
{
if (_instance != null)
return _instance;
_instance = FindObjectOfType<T>();
if (_instance != null)
return _instance;
var o = new GameObject($"{typeof(T).Name} (Singleton)");
_instance = o.AddComponent<T>();
return _instance;
}
}
[SuppressMessage("ReSharper", "VirtualMemberNeverOverridden.Global")]
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
if (Application.isPlaying)
{
DontDestroyOnLoad(gameObject);
}
}
else
{
if (Application.isPlaying)
{
Destroy(gameObject);
}
else
{
DestroyImmediate(gameObject);
}
}
}
}
}
Not PR-ing, just a suggestion :)
hasanbayatme commented
Thank you, that's a good idea, I'll add this coupled with #4 as a patch, let me know if you have any other ideas!
hasanbayatme commented
Thank you, that's a good idea, I'll add this coupled with #4 as a patch, let me know if you have any other ideas!
hasanbayatme commented
Added basic editor mode support on e902a9f