Skip to content

Instantly share code, notes, and snippets.

@BrodyB
Created January 22, 2017 18:27
Show Gist options
  • Save BrodyB/faa2899326094d2e78252251d5d2e4eb to your computer and use it in GitHub Desktop.
Save BrodyB/faa2899326094d2e78252251d5d2e4eb to your computer and use it in GitHub Desktop.
Unity extension method for GameObject that gets a component, or adds it if it doesn't exist.
using UnityEngine;
using System.Collections;
public static class ExtensionMethods
{
// Note: Making the parameter "this GameObject variableName" makes it an
// extension method for GameObject. Change it to Transform or whatever
// to make it a part of Transform, etc etc.
public static T GetOrAddComponent<T> (this GameObject obj) where T : Component
{
// Attempt to get component from GameObject
T retreivedComp = obj.GetComponent<T>();
if (retreivedComp != null)
return retreivedComp;
// This component wasn't found on the object, so add it.
return obj.AddComponent<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment