UI_Base
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class UI_Base : MonoBehaviour
{
Dictionary<Type, UnityEngine.Object[]> _objects = new Dictionary<Type, UnityEngine.Object[]>();
protected void Bind<T>(Type type) where T : UnityEngine.Object
{
string[] names = Enum.GetNames(type);
UnityEngine.Object[] objects = new UnityEngine.Object[names.Length];
_objects.Add(typeof(T), objects);
for (int i = 0; i < names.Length; i++)
{
if (typeof(T) == typeof(GameObject))
{
objects[i] = Utill.FindChild(gameObject, names[i], true);
}
else
{
objects[i] = Utill.FindChild<T>(gameObject, names[i], true);
}
}
}
protected T Get<T>(int index) where T : UnityEngine.Object
{
UnityEngine.Object[] objects = null;
if (_objects.TryGetValue(typeof(T), out objects) == false)
return null;
return objects[index] as T;
}
protected TMP_Text GetText(int index) { return Get<TMP_Text>(index); }
protected Button GetButton(int index) { return Get<Button>(index); }
protected Image GetImage(int index) { return Get<Image>(index); }
}
UI_Button
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class UI_Button : UI_Base
{
enum Texts
{
Text1,
Text2
}
enum Buttons
{
ButtonA,
ButtonB
}
enum GameObjects
{
CubeA,
CubeB
}
private void Start()
{
Bind<TMP_Text>(typeof(Texts));
Get<TMP_Text>((int)Texts.Text1).text = "unity";
Bind<GameObject>(typeof(GameObjects));
Get<GameObject>((int)GameObjects.CubeB).transform.Translate(new Vector3(20, 20, 20));
}
}
Utill
using UnityEngine;
public class Utill
{
public static GameObject FindChild(GameObject go, string name = null, bool recursive = false)
{
Transform transform = FindChild<Transform>(go, name, recursive);
if(transform == null)
return null;
return transform.gameObject;
}
public static T FindChild<T>(GameObject go, string name = null, bool recursive = false) where T : UnityEngine.Object
{
if (go == null)
return null;
if (recursive == false)
{
for (int i = 0; i < go.transform.childCount; i++)
{
Transform transform = go.transform.GetChild(i);
if (string.IsNullOrEmpty(name) || transform.name == name)
{
T component = transform.GetComponent<T>();
if (component != null)
return component;
}
}
}
else
{
foreach (T component in go.transform.GetComponentsInChildren<T>())
{
if (string.IsNullOrEmpty(name) || component.name == name)
{
return component;
}
}
}
return null;
}
}