com.alicizax.unity/Runtime/Extension/UnityEngage.GameObject/UnityEngage.GameObjectExtension.cs
2025-04-11 19:57:23 +08:00

103 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}
private static readonly List<Transform> s_CachedTransforms = new List<Transform>();
/// <summary>
/// 获取或增加组件。
/// </summary>
/// <typeparam name="T">要获取或增加的组件。</typeparam>
/// <param name="gameObject">目标对象。</param>
/// <returns>获取或增加的组件。</returns>
public static void DestroyComponent<T>(this GameObject gameObject) where T : Component
{
T component = gameObject.GetComponent<T>();
if (component != null)
{
Object.Destroy(component);
}
// return component;
}
/// <summary>
/// 获取或增加组件。
/// </summary>
/// <typeparam name="T">要获取或增加的组件。</typeparam>
/// <param name="gameObject">目标对象。</param>
/// <returns>获取或增加的组件。</returns>
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{
T component = gameObject.GetComponent<T>();
if (component == null)
{
component = gameObject.AddComponent<T>();
}
return component;
}
/// <summary>
/// 获取或增加组件。
/// </summary>
/// <param name="gameObject">目标对象。</param>
/// <param name="type">要获取或增加的组件类型。</param>
/// <returns>获取或增加的组件。</returns>
public static Component GetOrAddComponent(this GameObject gameObject, Type type)
{
Component component = gameObject.GetComponent(type);
if (component == null)
{
component = gameObject.AddComponent(type);
}
return component;
}
/// <summary>
/// 获取 GameObject 是否在场景中。
/// </summary>
/// <param name="gameObject">目标对象。</param>
/// <returns>GameObject 是否在场景中。</returns>
/// <remarks>若返回 true表明此 GameObject 是一个场景中的实例对象;若返回 false表明此 GameObject 是一个 Prefab。</remarks>
public static bool InScene(this GameObject gameObject)
{
return gameObject.scene.name != null;
}
/// <summary>
/// 递归设置游戏对象的层次。
/// </summary>
/// <param name="gameObject"><see cref="GameObject" /> 对象。</param>
/// <param name="layer">目标层次的编号。</param>
public static void SetLayerRecursively(this GameObject gameObject, int layer)
{
gameObject.GetComponentsInChildren(true, s_CachedTransforms);
foreach (var tf in s_CachedTransforms)
{
tf.gameObject.layer = layer;
}
s_CachedTransforms.Clear();
}
}
}