GetOrAddComponent

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
(Created page with "Category: MonoBehaviour Category: C Sharp Author: Caue Rego (cawas) == Description == Simple method extension to save 2 or 3 lines of very redundant and ugly code. It...")
 
m (Included in Extension Scripts category)
Line 1: Line 1:
 
[[Category: MonoBehaviour]]
 
[[Category: MonoBehaviour]]
 
[[Category: C Sharp]]
 
[[Category: C Sharp]]
 +
[[Category Extension Scripts]]
 
Author: Caue Rego (cawas)
 
Author: Caue Rego (cawas)
  

Revision as of 11:07, 28 February 2013

Category Extension Scripts 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;
	}
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox