Skip to content

Instantly share code, notes, and snippets.

@nailuj05
Last active October 19, 2024 08:41
Show Gist options
  • 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