using System;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using static UnityEngine.GraphicsBuffer;
public class ControlComponent : MonoBehaviour
{
Dictionary<string, UnityEngine.Component> d_obj;
public void Awake()
{
d_obj = new Dictionary<string, UnityEngine.Component>();
// 定义你想要查找的组件类型
Type[] componentTypes = { typeof(Image), typeof(Text), typeof(Button) };
foreach (Type type in componentTypes)
{
//d_obj.AddRange(targetObject.GetComponentsInChildren(type, true));
UnityEngine.Component[] coms = this.gameObject.GetComponentsInChildren(type, true);
foreach (UnityEngine.Component target in coms)
{
d_obj.TryAdd(target.name, target);
}
}
}
public T GetComponetMul<T>(string name) where T : UnityEngine.Component
{
UnityEngine.Component d_comp;
if (d_obj.TryGetValue(name, out d_comp))
{
T d = d_comp.GetComponent<T>();
if (d == null)
{
d = d_comp.AddComponent<T>();
}
return d;
}
return null;
}
private void OnDestroy()
{
d_obj.Clear();
d_obj = null;
}
}
使用方法:在类中继承ControlComponent
using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using UnityEngine;
using UnityEngine.UI;
public class RankFSTHView : ControlComponent
{
HeroSpinLoad heroSpine;
long id;
private EntityManager entityManager;
private PlayerDataComponent playerData;
private void Start()
{
entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
playerData = entityManager.GetComponentData<PlayerDataComponent>(GlobalVariables.PlayerDataEntity);
Transform spine = this.transform.Find("spine");
heroSpine = spine.gameObject.AddComponent<HeroSpinLoad>();
UnityTools.AddClickEventToButton(this.GetComponent<Button>(), OnOpenRankInfoPanel);
}
public void UpdateUI(_RANK_ITEM data, int type)
{
id = data.Id;
Text nameTxt = GetComponetMul<Text>("nameTxt");
nameTxt.text = playerData.Id == (ulong)data.Id ? playerData.Name.ToString(): data.Name;
Text levelTxt = GetComponetMul<Text>("levelTxt");
if (type == 1)
{
levelTxt.text = string.Format("{0}层", data.Score);
}
else {
levelTxt.text = string.Format("{0}", data.Score);
}
if (data.HeroId > 0)
{
heroSpine.LoadHeroSpine(data.HeroId);
}
}
private void OnOpenRankInfoPanel()
{
UIHelp.CreateUI<OneRankPanel_View>(null, null, id);
}
}
比如 Text nameTxt = GetComponetMul<Text>("nameTxt");可以直接获取相关的组件