67 lines
1.7 KiB
C#
67 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using AibisDream.Kit;
|
|
using AibisDream.Utility;
|
|
using UnityEngine;
|
|
#if UNITY_EDITOR
|
|
using UnityEditor;
|
|
#endif
|
|
|
|
namespace AibisDream
|
|
{
|
|
public class GlobalDataContainer : SingletonBase<GlobalDataContainer>
|
|
{
|
|
private Dictionary<Type, object> _dataDict;
|
|
|
|
public override void OnSingletonInit()
|
|
{
|
|
_dataDict = new Dictionary<Type, object>();
|
|
// 收集数据并初始化
|
|
var globalDataTypes = CommonUtil.FindTypesWithAttribute<GlobalDataAttribute>();
|
|
foreach (var globalDataType in globalDataTypes)
|
|
{
|
|
object instance = Activator.CreateInstance(globalDataType);
|
|
_dataDict.Add(globalDataType, instance);
|
|
}
|
|
}
|
|
|
|
public T GetData<T>() where T : class
|
|
{
|
|
if (_dataDict.TryGetValue(typeof(T), out var data))
|
|
{
|
|
return data as T;
|
|
}
|
|
|
|
Debug.LogError($"没有找到{typeof(T)}");
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 用于单例模式
|
|
/// </summary>
|
|
private GlobalDataContainer()
|
|
{
|
|
#if UNITY_EDITOR
|
|
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
|
|
#endif
|
|
}
|
|
|
|
#if UNITY_EDITOR
|
|
private void OnPlayModeStateChanged(PlayModeStateChange state)
|
|
{
|
|
if (state == PlayModeStateChange.ExitingEditMode)
|
|
{
|
|
OnSingletonInit();
|
|
}
|
|
}
|
|
#endif
|
|
}
|
|
|
|
/// <summary>
|
|
/// 全局数据属性
|
|
/// </summary>
|
|
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
|
|
public class GlobalDataAttribute : Attribute
|
|
{
|
|
}
|
|
} |