init
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RPGCore.Core;
|
||||
using RPGCore.Core.Objects;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RPGCore.ObjectModules.EventObjectModule
|
||||
{
|
||||
[Serializable]
|
||||
[RequireComponent(typeof(BaseObject))]
|
||||
public class DataModule : ObjectModule<BaseObject>
|
||||
{
|
||||
// SERIALIZED
|
||||
[SerializeReference] private List<BaseData> _dataList = new();
|
||||
|
||||
// RUNTIME
|
||||
private Dictionary<Type, BaseData> _dataDict;
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
if (!parent) return;
|
||||
|
||||
// Remove invalid
|
||||
if (_dataList.Any(data => data == null))
|
||||
_dataList = _dataList.Where(data => data != null).ToList();
|
||||
|
||||
// Remove duplicates
|
||||
if (_dataList.GroupBy(data => data.GetType()).Any(g => g.Count() > 1))
|
||||
_dataList = _dataList.GroupBy(data => data.GetType()).Select(g => g.First()).ToList();
|
||||
|
||||
// Create missing datas
|
||||
UnityEditor.TypeCache.GetTypesDerivedFrom<BaseObject>()
|
||||
.Append(typeof(BaseObject))
|
||||
.Where(t => t.IsAssignableFrom(parent.GetType()))
|
||||
.Select(t => typeof(BaseData<>).MakeGenericType(t))
|
||||
.SelectMany(t => UnityEditor.TypeCache.GetTypesDerivedFrom(t))
|
||||
.Where(t => !_dataList.Select(data => data.GetType()).Contains(t))
|
||||
.ToList().ForEach(t => _dataList.Add(Activator.CreateInstance(t) as BaseData));
|
||||
|
||||
_dataList.ForEach(data => data.parent = parent);
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_dataDict = _dataList.ToDictionary(data => data.GetType(), data => data);
|
||||
}
|
||||
|
||||
public T Get<T>() where T : BaseData
|
||||
{
|
||||
return (T)_dataDict[typeof(T)];
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user