using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BaseView : MonoBehaviour { public Canvas Canvas { get { return GameObject.FindObjectOfType(); } } protected virtual void Awake() { OnInit(this.gameObject); } protected virtual void OnInit(GameObject obj) { SetActive(this.gameObject.transform); } protected void SetActive(T obj, bool state = true) where T: Component { if(obj == null) { Debug.LogError("传入对象为空"); return; } obj.gameObject.SetActive(state); } protected void SetActive(GameObject obj, bool state = true) { if (obj == null) { Debug.LogError("传入对象为空"); return; } obj.SetActive(state); } protected void AddListener(Button btn, Action action) { if (btn != null) { btn.onClick.AddListener(() => { if (action != null) { action(); } }); } else { Debug.LogError(btn.name + "对象的身上的Button组件为null"); } } protected void SetText(Text txt, string context = "") { if (txt != null) txt.text = context; } /// /// 递归查找子对象 /// /// /// /// public GameObject GetChild(Transform trans, string childName) { Transform child = trans.Find(childName); if (child != null) { return child.gameObject; } int count = trans.childCount; GameObject go = null; int idx = 0; while (idx < count) { child = trans.GetChild(idx); go = GetChild(child, childName); if (go != null) { return go; } idx++; } return null; } public T GetChild(Transform trans, string childName) where T : Component { if (trans == null) { Debug.LogError("传入父物体为空。无法查找"); return default(T); } GameObject go = GetChild(trans, childName); if (go == null) { Debug.LogWarning("查找到的对象为 空。无法获取"); return null; } return go.GetComponent(); } }