Files
BITKit/Src/Unity/Scripts/Extensions/GameObjectExtensions.cs
CortexCore c3f0a8e840 1
2025-08-03 02:28:50 +08:00

35 lines
803 B
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit
{
public static class GameObjectExtensions
{
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{
return gameObject.TryGetComponent<T>(out var t) ? t : gameObject.AddComponent<T>();
}
public static T RemoveComponent<T>(this GameObject gameObject) where T : Component
{
var t = gameObject.GetComponent<T>();
if (t is null) return null;
Object.Destroy(t);
return t;
}
public static int RemoveComponentsInChildren<T>(this GameObject gameObject) where T :Component
{
var count = 0;
foreach (var x in gameObject.GetComponentsInChildren<T>())
{
if (!x) continue;
Object.Destroy(x);
count++;
}
return count;
}
}
}