using UnityEngine.Assertions;
namespace UnityEngine
{
///
/// .
///
public static class ComponentExtensions
{
///
/// 从目标组件中获取一个组件,如果是组件类型不存在,则添加
///
public static Component GetOrAddComponent(
this Component obj, System.Type type)
{
var component = obj.GetComponent(type);
if (component == null)
{
component = obj.gameObject.AddComponent(type);
}
return component;
}
///
/// 从目标组件中获取一个组件,如果是组件类型不存在,则添加
///
public static T GetOrAddComponent(
this Component obj) where T : Component
{
var component = obj.GetComponent();
if (component == null)
{
component = obj.gameObject.AddComponent();
}
return component;
}
///
/// 从目标组件中获取一个组件,如果是组件类型不存在,则添加
/// 标记不保存
///
public static T GetOrAddComponentDontSave(
this Component obj) where T : Component
{
var component = obj.GetComponent();
if (component == null)
{
component = obj.gameObject.AddComponent();
component.hideFlags = HideFlags.DontSave;
}
return component;
}
///
/// 检查目标组件的GameObject上是否有一个或多个指定类型的组件
///
public static bool HasComponent(
this Component obj, System.Type type)
{
return obj.GetComponent(type) != null;
}
///
/// 检查目标组件的GameObject上是否有一个或多个指定类型的组件
///
public static bool HasComponent(
this Component obj) where T : Component
{
return obj.GetComponent() != null;
}
///
/// 在parent中查找组件,即使该组件处于非活动状态或已禁用 都能查询
///
public static T GetComponentInParentHard(
this Component obj) where T : Component
{
Assert.IsNotNull(obj);
var transform = obj.transform;
while (transform != null)
{
var component = transform.GetComponent();
if (component != null)
{
return component;
}
transform = transform.parent;
}
return null;
}
}
}