78 lines
2.0 KiB
C#
78 lines
2.0 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using Sirenix.OdinInspector;
|
||
using UnityEngine;
|
||
|
||
namespace ZC
|
||
{
|
||
public class GameObjectBinding : MonoBehaviour
|
||
{
|
||
[SerializeField] private List<GameObjectBindingData> Datas = new List<GameObjectBindingData>();
|
||
|
||
#if UNITY_EDITOR
|
||
public IReadOnlyList<GameObjectBindingData> AllData => Datas;
|
||
|
||
public void ClearValue()
|
||
{
|
||
Datas.Clear();
|
||
}
|
||
|
||
public void AddValue(Transform trans)
|
||
{
|
||
foreach (var data in Datas)
|
||
{
|
||
if (data.name == trans.name)
|
||
{
|
||
throw new ArgumentException($"重复添加了, {trans.name}");
|
||
}
|
||
}
|
||
|
||
Datas.Add(new GameObjectBindingData() { name = trans.name, go = trans.gameObject });
|
||
}
|
||
#endif
|
||
|
||
public GameObject GetValue(string nameStr)
|
||
{
|
||
foreach (var data in Datas)
|
||
{
|
||
if (data.name == nameStr)
|
||
{
|
||
return data.go;
|
||
}
|
||
}
|
||
|
||
throw new NullReferenceException($"没有找到绑定这个名字的物体,name:{nameStr}");
|
||
}
|
||
|
||
public T GetValue<T>(string nameStr) where T : Component
|
||
{
|
||
foreach (var data in Datas)
|
||
{
|
||
if (data.name == nameStr)
|
||
{
|
||
return data.go.GetComponent<T>();
|
||
}
|
||
}
|
||
|
||
throw new NullReferenceException($"没有找到绑定这个名字的物体,name:{nameStr}");
|
||
}
|
||
}
|
||
|
||
[System.Serializable]
|
||
public class GameObjectBindingData
|
||
{
|
||
[HorizontalGroup("aaa")] [LabelText("k"), LabelWidth(10)]
|
||
public string name;
|
||
|
||
[HorizontalGroup("aaa")] [LabelText("v"), LabelWidth(10)] [OnValueChanged(nameof(OnValueChanged))]
|
||
public GameObject go;
|
||
|
||
private void OnValueChanged()
|
||
{
|
||
if (go != null)
|
||
name = go.name;
|
||
else
|
||
name = string.Empty;
|
||
}
|
||
}
|
||
} |