Created
January 22, 2017 18:27
-
-
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.
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
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