95 lines
2.9 KiB
C#
95 lines
2.9 KiB
C#
using UnityEngine;
|
|
|
|
/// <summary>
|
|
/// 组件拓展
|
|
/// </summary>
|
|
public static class ComponentExtend
|
|
{
|
|
/// <summary>
|
|
/// 获取某对象下的子物体,适用于多层级父子关系的查找
|
|
/// </summary>
|
|
/// <param name="self">子物体名称</param>
|
|
/// <param name="objName"></param>
|
|
/// <returns></returns>
|
|
public static Transform FindChildByName(this Component self, string objName)
|
|
{
|
|
if (self == null || string.IsNullOrEmpty(objName)) return null;
|
|
|
|
Transform[] children = self.GetComponentsInChildren<Transform>(true);
|
|
|
|
for (int i = 0; i < children.Length; i++)
|
|
{
|
|
if (children[i].name.Equals(objName))
|
|
return children[i];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取某物体下的子物体上的某个组件,适用于多层级父子关系的查找
|
|
/// </summary>
|
|
/// <typeparam name="T">组件类型</typeparam>
|
|
/// <param name="self"></param>
|
|
/// <param name="objNmae">子物体名称</param>
|
|
/// <returns></returns>
|
|
public static T GetComponentByChildName<T>(this Component self, string objNmae) where T : Component
|
|
{
|
|
Transform tf = FindChildByName(self, objNmae);
|
|
if (tf != null)
|
|
return tf.GetComponent<T>();
|
|
else
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 自动检查并添加组件
|
|
/// </summary>
|
|
/// <typeparam name="T">组件类型</typeparam>
|
|
/// <param name="self">添加组件的Component</param>
|
|
/// <param name="CoverModel">是否删除已有并重新添加组件</param>
|
|
/// <returns></returns>
|
|
public static T AutoComponent<T>(this Component self, bool CoverModel = false) where T : Component
|
|
{
|
|
if (CoverModel)
|
|
{
|
|
if (self.TryGetComponent(out T destroy))
|
|
Object.Destroy(destroy);
|
|
|
|
return self.gameObject.AddComponent<T>();
|
|
}
|
|
else
|
|
{
|
|
if (self.TryGetComponent(out T component))
|
|
return component;
|
|
else
|
|
return self.gameObject.AddComponent<T>();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 自动检查并添加组件
|
|
/// </summary>
|
|
/// <typeparam name="T">组件类型</typeparam>
|
|
/// <param name="self">添加组件的GameObject</param>
|
|
/// <param name="CoverModel">是否删除已有并重新添加组件</param>
|
|
/// <returns></returns>
|
|
public static T AutoComponent<T>(this GameObject self, bool CoverModel = false) where T : Component
|
|
{
|
|
if (CoverModel)
|
|
{
|
|
if (self.TryGetComponent(out T destroy))
|
|
Object.Destroy(destroy);
|
|
return self.gameObject.AddComponent<T>();
|
|
}
|
|
else
|
|
{
|
|
if(self.TryGetComponent(out T component))
|
|
return component;
|
|
else
|
|
return self.gameObject.AddComponent<T>();
|
|
}
|
|
}
|
|
|
|
}
|