Created
May 27, 2025 20:13
-
-
Save ababilinski/b5fbed0b2b1b4838c2168631e4c7b29d to your computer and use it in GitHub Desktop.
Extension helpers that either return an existing component or add one if it doesn’t exist.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Extension helpers that either return an existing component | |
| // or add one if it doesn’t exist—zero allocations. | |
| // | |
| // Usage examples: | |
| // | |
| // var rb = gameObject.GetOrAddComponent<Rigidbody>(); | |
| // var cam = this.GetOrAddComponentInChildren<Camera>(includeInactive: true); | |
| // | |
| using UnityEngine; | |
| using System.Runtime.CompilerServices; | |
| namespace Common.Extensions | |
| { | |
| public static class GetOrAddComponentExtensions | |
| { | |
| // ---------- GameObject ------------------------------------------------ | |
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | |
| public static T GetOrAddComponent<T>(this GameObject go) where T : Component | |
| { | |
| #if UNITY_2022_2_OR_NEWER | |
| if (go.TryGetComponent(out T component)) return component; | |
| #else | |
| T component = go.GetComponent<T>(); | |
| if (component) return component; | |
| #endif | |
| return go.AddComponent<T>(); | |
| } | |
| /// <summary> | |
| /// Returns the first <typeparamref name="T"/> in children, or adds one | |
| /// to the root GameObject if none exists. Optionally includes inactive children. | |
| /// </summary> | |
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | |
| public static T GetOrAddComponentInChildren<T>( | |
| this GameObject go, bool includeInactive = false) where T : Component | |
| { | |
| var component = go.GetComponentInChildren<T>(includeInactive); | |
| if (component) return component; | |
| return go.AddComponent<T>(); | |
| } | |
| // ---------- Component (MonoBehaviour / Transform) --------------------- | |
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | |
| public static T GetOrAddComponent<T>(this Component self) where T : Component => | |
| self.gameObject.GetOrAddComponent<T>(); | |
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | |
| public static T GetOrAddComponentInChildren<T>( | |
| this Component self, bool includeInactive = false) where T : Component => | |
| self.gameObject.GetOrAddComponentInChildren<T>(includeInactive); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment