Last active
October 19, 2024 08:41
-
-
Save nailuj05/21f1851ba788bd531cbc8f7ea8db0b78 to your computer and use it in GitHub Desktop.
A simple extension method for Unity C# this gets or adds a given Component. (SphereCollider coll = gameObject.GetOrAddComponent<SphereCollider>();)
This file contains 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
public static class Extensions | |
{ | |
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component | |
{ | |
if(gameObject.TryGetComponent<T>(out T t)) | |
{ | |
return t; | |
} | |
else | |
{ | |
return gameObject.AddComponent<T>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple extension method that saved me countless lines of redundant code