Some times you need to make sure a component has been set on a game object and if it does not exist add it.
/// <summary>
/// Tries to get a component and if it does not exist adds the component and returns a reference to it.
/// </summary>
/// <remarks>
/// <example>
/// Usage example:
/// <code>
/// var boxCollider = transform.GetOrAddComponent<BoxCollider>();
/// </code>
/// </example>
/// </remarks>
public static T GetOrAddComponent<T>(this Component child) where T : Component
{
var result = child.GetComponent<T>();
if (result == null)
{
result = child.gameObject.AddComponent<T>();
}
return result;
}