Skip to content

Instantly share code, notes, and snippets.

@nailuj05
Last active April 25, 2024 13:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nailuj05/21f1851ba788bd531cbc8f7ea8db0b78 to your computer and use it in GitHub Desktop.
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>();)
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>();
}
}
}
@nailuj05
Copy link
Author

nailuj05 commented Nov 5, 2021

A simple extension method that saved me countless lines of redundant code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment