GetOrAddComponent
From Unify Community Wiki
Revision as of 11:07, 28 February 2013 by Createdbyx (Talk | contribs)
Author: Caue Rego (cawas)
Description
Simple method extension to save 2 or 3 lines of very redundant and ugly code. It will check if component exists before adding new one.
Usage
This is just an instance. It could be, of course, any component.
BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
MonoBehaviourExtended.cs
static public class MethodExtensionForMonoBehaviourTransform { /// <summary> /// Gets or add a component. Usage example: /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>(); /// </summary> static public T GetOrAddComponent<T> (this Component child) where T: Component { T result = child.GetComponent<T>(); if (result == null) { result = child.gameObject.AddComponent<T>(); } return result; } }