GetOrAddComponent

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Bah! forgot the colon!)
(Greatly improved the code)
 
Line 1: Line 1:
[[Category: MonoBehaviour]]
+
This simple extension method will prevent you from having to write very redundant and ugly code every time you need to get a component but are not sure if it actually exist already.
[[Category: C Sharp]]
+
[[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 [http://docs.unity3d.com/Documentation/ScriptReference/Component.html component].
+
  
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
+
using UnityEngine;
 +
 
 +
static public class UnityEngineExtensions
 +
{
 +
    /// <summary>
 +
    /// Returns the component of Type type. If one doesn't already exist on the GameObject it will be added.
 +
    /// </summary>
 +
    /// <typeparam name="T">The type of Component to return.</typeparam>
 +
    /// <param name="gameObject">The GameObject this Component is attached to.</param>
 +
    /// <returns>Component</returns>
 +
    static public T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
 +
    {
 +
        return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>();
 +
    }
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== MonoBehaviourExtended.cs ==
+
== Usage ==
 +
Create a new script named '''UnityEngineExtensions''' or whatever you like and put the above code in it. Then simply replace any '''GetComponent''' calls with '''GetOrAddComponent''' to ensure the component exist without having to check for null.
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
static public class MethodExtensionForMonoBehaviourTransform {
+
using UnityEngine;
/// <summary>
+
 
/// Gets or add a component. Usage example:
+
public class ExampleScript : MonoBehaviour
/// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
+
{
/// </summary>
+
    Rigidbody m_Body;
static public T GetOrAddComponent<T> (this Component child) where T: Component {
+
 
T result = child.GetComponent<T>();
+
    void Awake()
if (result == null) {
+
    {
result = child.gameObject.AddComponent<T>();
+
        m_Body = gameObject.GetOrAddComponent<Rigidbody>();
}
+
    }
return result;
+
}
+
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
[[Category: C Sharp]]
 +
[[Category: Extensions]]

Latest revision as of 23:54, 3 February 2019

This simple extension method will prevent you from having to write very redundant and ugly code every time you need to get a component but are not sure if it actually exist already.

using UnityEngine;
 
static public class UnityEngineExtensions
{
    /// <summary>
    /// Returns the component of Type type. If one doesn't already exist on the GameObject it will be added.
    /// </summary>
    /// <typeparam name="T">The type of Component to return.</typeparam>
    /// <param name="gameObject">The GameObject this Component is attached to.</param>
    /// <returns>Component</returns>
    static public T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
    {
        return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>();
    }
}

[edit] Usage

Create a new script named UnityEngineExtensions or whatever you like and put the above code in it. Then simply replace any GetComponent calls with GetOrAddComponent to ensure the component exist without having to check for null.

using UnityEngine;
 
public class ExampleScript : MonoBehaviour
{
    Rigidbody m_Body;
 
    void Awake()
    {
        m_Body = gameObject.GetOrAddComponent<Rigidbody>();
    }
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox