BITKit/Packages/Runtime/Root/Root.cs

65 lines
1.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
using System.Linq;
namespace BITKit
{
public static partial class Extensions
{
public static bool TryGetRoot(this Component self, out Root root)
{
root = null;
try
{
if (self is not null && self.TryGetComponent<Root>(out root))
{
root = root.root;
return true;
}
}
catch (System.Exception)
{
return false;
}
return false;
}
}
public class Root : SerializedMonoBehaviour
{
[Header(Constant.Header.Settings)]
public Root root;
public string id;
[Header(Constant.Header.Gameobjects)]
public Dictionary<string, Root> childs = new();
public Root Get(string id)
{
if (id.IsNullOrEmpty())
{
return this;
}
else
{
return childs[id];
}
}
[Button]
void AutoSetUp()
{
if (id.IsNullOrEmpty())
{
id = name;
}
childs.Clear();
if (root == this)
{
GetComponentsInChildren<Root>(true)
.Where(x => x.root == root)
.ForEach(x =>
{
childs.TryAdd(x.id, x);
});
}
}
}
}