unitycommunity / unitysingleton Goto Github PK
View Code? Open in Web Editor NEWThe best way to implement singleton pattern in Unity.
Home Page: https://en.wikipedia.org/wiki/Singleton_pattern
License: MIT License
The best way to implement singleton pattern in Unity.
Home Page: https://en.wikipedia.org/wiki/Singleton_pattern
License: MIT License
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
//If there is already an instance of this class, destroy the object we just created.
Debug.LogWarning("Attempted to spawn more then one singleton object. destroying new instance of " + gameObject.ToString() + "\nIf you would like more than one instance, ensure that the class you have written does not Inherit from a Singleton class.");
Destroy(gameObject);
}
}
I found another snippet from Naphier which the instance!=this
make sense when destroy it.
Could you please explain it why you didn't add condition? Thanks.
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 :)
In some cases we should use this pattern, it differs from the traditional "Global singleton pattern", the purpose of "Scene Singleton Pattern" is to ensure that there is only one instance of the class in a given scene, but it does not require that instance to persist across scenes. This pattern is useful when you need to manage certain assets or features in a single scene, but you don't want those assets or features to remain present when the scene is switched.
Maybe it's better to have a singleton class which is not extended from Monobehaviour. And it can be used to add some class to manager global data or implement data.
Add Unity Package Manager setup instructions and include package.json file.
protected virtual void Awake() {
if (_instance == null) {
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else {
Destroy(gameObject);
}
}
The Awake()
function is the key part to make the derived singleton class persistent across scenes and prevent duplicates, but it is marked as protected virtual
, so that one could accidentally override it but forgot to add the base.Awake()
call, which would then break things apart, and it's hard to debug...
I think maybe we can improve by doing sth like this?
private void Awake() {
if (_instance == null) {
_instance = this as T;
DontDestroyOnLoad(gameObject);
Initialize();
}
else {
Destroy(gameObject);
}
}
protected virtual void Initialize() { }
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.