using System;
using System.Collections.Generic;
using UnityEngine;
namespace XGame.Framework.ObjectCollection
{
[Serializable]
public class ObjectCollector : IObjectCollector
{
#if UNITY_EDITOR
public Type collectorType = typeof(GameObject);
public Type[] blackTypes = null;
///
/// 绑定的脚本类型,生成代码用
///
[SerializeField]
public List bindTypes = new List();
#endif
[SerializeField]
public List keys = new List();
[SerializeField]
public List values = new List();
private Dictionary _objectsMap;
private bool _isInited = false;
public UnityEngine.Object this[string key]
{
get
{
if (!_isInited) CacheDict();
if (_objectsMap.TryGetValue(key, out UnityEngine.Object value))
return value;
Log.Debug($"Can't find the key: {key}, Please Check it");
return null;
}
}
public List Keys => keys;
public List Objects => values;
public T GetComponent(string key) where T : Component
{
var obj = this[key];
if (obj is GameObject go)
{
return go.GetComponent();
}
if (obj is Component component)
{
return component.gameObject.GetComponent();
}
//Log.Debug($"Can't find Component. key: {key} Type:{typeof(T)}");
return null;
}
public GameObject GetGameObject(string key)
{
var obj = this[key];
if (obj is GameObject go)
{
return go;
}
if (obj is Component component)
{
return component.gameObject;
}
Log.Error($"Can't find GameObject. key: {key}");
return null;
}
private void CacheDict()
{
_isInited = true;
_objectsMap = new Dictionary(keys.Count);
for (int i = 0, length = keys.Count; i < length; i++)
{
_objectsMap[keys[i]] = values[i];
}
}
}
}