using System;
using System.Collections.Generic;
namespace UnityEngine
{
public static class UnityEngageGameObjectExtension
{
public static void SafeDestroySelf(
this Object obj)
{
if (obj == null) return;
#if UNITY_EDITOR
if (!Application.isPlaying)
Object.DestroyImmediate(obj);
else
Object.Destroy(obj);
#else
Object.Destroy(obj);
#endif
}
///
/// 获取或增加组件。
///
/// 要获取或增加的组件。
/// 目标对象。
/// 获取或增加的组件。
public static void DestroyComponent(this GameObject gameObject) where T : Component
{
T component = gameObject.GetComponent();
if (component != null)
{
Object.Destroy(component);
}
// return component;
}
///
/// 获取或增加组件。
///
/// 要获取或增加的组件。
/// 目标对象。
/// 获取或增加的组件。
public static T GetOrAddComponent(this GameObject gameObject) where T : Component
{
T component = gameObject.GetComponent();
if (component == null)
{
component = gameObject.AddComponent();
}
return component;
}
///
/// 获取或增加组件。
///
/// 目标对象。
/// 要获取或增加的组件类型。
/// 获取或增加的组件。
public static Component GetOrAddComponent(this GameObject gameObject, Type type)
{
Component component = gameObject.GetComponent(type);
if (component == null)
{
component = gameObject.AddComponent(type);
}
return component;
}
///
/// 获取 GameObject 是否在场景中。
///
/// 目标对象。
/// GameObject 是否在场景中。
/// 若返回 true,表明此 GameObject 是一个场景中的实例对象;若返回 false,表明此 GameObject 是一个 Prefab。
public static bool InScene(this GameObject gameObject)
{
return gameObject.scene.name != null;
}
}
}