ar_tourism_flutter_unity/unity/VRProject2/Assets/FlutterUnityIntegration/SingletonMonoBehaviour.cs
2025-05-14 17:04:13 +08:00

20 lines
594 B
C#

using System;
using UnityEngine;
namespace FlutterUnityIntegration
{
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
private static readonly Lazy<T> LazyInstance = new Lazy<T>(CreateSingleton);
public static T Instance => LazyInstance.Value;
private static T CreateSingleton()
{
var ownerObject = new GameObject($"{typeof(T).Name} (singleton)");
var instance = ownerObject.AddComponent<T>();
DontDestroyOnLoad(ownerObject);
return instance;
}
}
}