// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit
{
///
/// Extensions methods for the Unity Component class.
/// This also includes some component-related extensions for the GameObject class.
///
public static class ComponentExtensions
{
///
/// Ensure that a component of type exists on the game object.
/// If it doesn't exist, creates it.
///
/// Type of the component.
/// A component on the game object for which a component of type should exist.
/// The component that was retrieved or created.
public static T EnsureComponent(this Component component) where T : Component
{
return EnsureComponent(component.gameObject);
}
///
/// Find the first component of type in the ancestors of the game object of the specified component.
///
/// Type of component to find.
/// Component for which its game object's ancestors must be considered.
/// Indicates whether the specified game object should be included.
/// The component of type . Null if it none was found.
public static T FindAncestorComponent(this Component component, bool includeSelf = true) where T : Component
{
return component.transform.FindAncestorComponent(includeSelf);
}
///
/// Ensure that a component of type exists on the game object.
/// If it doesn't exist, creates it.
///
/// Type of the component.
/// Game object on which component should be.
/// The component that was retrieved or created.
///
/// This extension has to remain in this class as it is required by the method
///
public static T EnsureComponent(this GameObject gameObject) where T : Component
{
T foundComponent = gameObject.GetComponent();
return foundComponent == null ? gameObject.AddComponent() : foundComponent;
}
///
/// Ensure that a component of type exists on the game object.
/// If it doesn't exist, creates it.
///
/// A component on the game object for which a component of type should exist.
/// The component that was retrieved or created.
public static Component EnsureComponent(this GameObject gameObject, Type component)
{
var foundComponent = gameObject.GetComponent(component);
return foundComponent == null ? gameObject.AddComponent(component) : foundComponent;
}
}
}