From 7a1d5931957f1b77baf0ba304e549d847332c969 Mon Sep 17 00:00:00 2001 From: ALEXTANG <574809918@qq.com> Date: Wed, 5 Jul 2023 15:20:12 +0800 Subject: [PATCH] Update UnityExtension.cs --- .../Runtime/Extension/UnityExtension.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Assets/TEngine/Runtime/Extension/UnityExtension.cs b/Assets/TEngine/Runtime/Extension/UnityExtension.cs index c413abdb..81562c2d 100644 --- a/Assets/TEngine/Runtime/Extension/UnityExtension.cs +++ b/Assets/TEngine/Runtime/Extension/UnityExtension.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using JetBrains.Annotations; using UnityEngine; +using UnityEngineInternal; /// /// 对 Unity 的扩展方法。 @@ -18,11 +20,13 @@ public static class UnityExtension public static T GetOrAddComponent(this GameObject gameObject) where T : Component { T component = gameObject.GetComponent(); + if (component == null) { component = gameObject.AddComponent(); } + return component; } @@ -35,6 +39,7 @@ public static class UnityExtension public static Component GetOrAddComponent(this GameObject gameObject, Type type) { Component component = gameObject.GetComponent(type); + if (component == null) { component = gameObject.AddComponent(type); @@ -42,6 +47,40 @@ public static class UnityExtension return component; } + + /// + /// 移除组件。 + /// + /// 目标对象。 + /// 要获取或增加的组件类型。 + /// + [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); + } + } + + /// + /// 移除组件。 + /// + /// 目标对象。 + /// 要获取或增加的组件类型。 + public static void RemoveMonoBehaviour(this GameObject gameObject) where T : Component + { + T component = gameObject.GetComponent(); + + if (component != null) + { + UnityEngine.Object.Destroy(component); + } + } /// /// 获取 GameObject 是否在场景中。