Update UnityExtension.cs

This commit is contained in:
ALEXTANG
2023-07-05 15:20:12 +08:00
parent bc113c5c6e
commit 7a1d593195

View File

@@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine; using UnityEngine;
using UnityEngineInternal;
/// <summary> /// <summary>
/// 对 Unity 的扩展方法。 /// 对 Unity 的扩展方法。
@@ -18,11 +20,13 @@ public static class UnityExtension
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{ {
T component = gameObject.GetComponent<T>(); T component = gameObject.GetComponent<T>();
if (component == null) if (component == null)
{ {
component = gameObject.AddComponent<T>(); component = gameObject.AddComponent<T>();
} }
return component; return component;
} }
@@ -35,6 +39,7 @@ public static class UnityExtension
public static Component GetOrAddComponent(this GameObject gameObject, Type type) public static Component GetOrAddComponent(this GameObject gameObject, Type type)
{ {
Component component = gameObject.GetComponent(type); Component component = gameObject.GetComponent(type);
if (component == null) if (component == null)
{ {
component = gameObject.AddComponent(type); component = gameObject.AddComponent(type);
@@ -43,6 +48,40 @@ public static class UnityExtension
return component; return component;
} }
/// <summary>
/// 移除组件。
/// </summary>
/// <param name="gameObject">目标对象。</param>
/// <param name="type">要获取或增加的组件类型。</param>
/// <exception cref="ArgumentNullException"></exception>
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public static void RemoveMonoBehaviour(this GameObject gameObject,[NotNull] Type type)
{
if (type == null) throw new ArgumentNullException(nameof(type));
Component component = gameObject.GetComponent(type);
if (component != null)
{
UnityEngine.Object.Destroy(component);
}
}
/// <summary>
/// 移除组件。
/// </summary>
/// <param name="gameObject">目标对象。</param>
/// <typeparam name="T">要获取或增加的组件类型。</typeparam>
public static void RemoveMonoBehaviour<T>(this GameObject gameObject) where T : Component
{
T component = gameObject.GetComponent<T>();
if (component != null)
{
UnityEngine.Object.Destroy(component);
}
}
/// <summary> /// <summary>
/// 获取 GameObject 是否在场景中。 /// 获取 GameObject 是否在场景中。
/// </summary> /// </summary>