You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
2.6 KiB

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<Canvas>();
}
}
protected virtual void Awake()
{
OnInit(this.gameObject);
}
protected virtual void OnInit(GameObject obj)
{
SetActive<Transform>(this.gameObject.transform);
}
protected void SetActive<T>(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;
}
/// <summary>
/// 递归查找子对象
/// </summary>
/// <param name="trans"></param>
/// <param name="childName"></param>
/// <returns></returns>
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<T>(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<T>();
}
}