From Unify Community Wiki
Revision as of 23:54, 3 February 2019 by Isaiah Kelly (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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>();


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