/**
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
using UnityEngine;
namespace Live2D.Cubism.Framework
{
///
/// Extensions for s.
///
internal static class ObjectExtensionMethods
{
///
/// Extracts an interface from an .
///
/// Interface type to extract.
/// .
/// Valid reference on success; otherwise.
public static T GetInterface(this Object self) where T : class
{
var result = self as T;
if (result != null)
{
return result;
}
// Deal with GameObjects.
var gameObject = self as GameObject;
if (gameObject != null)
{
result = gameObject.GetComponent();
}
// Warn on error.
if (self != null && result == null)
{
Debug.LogWarning(self + " doesn't expose requested interface of type \"" + typeof(T) + "\".");
}
return result;
}
///
/// Nulls reference in case an doesn't expose an interface requested.
///
/// Type of interface to check for.
/// .
/// if object exposes interface; otherwise.
public static Object ToNullUnlessImplementsInterface(this Object self) where T : class
{
var exposesInterface = self.ImplementsInterface();
// Warn on error.
if (self != null && !exposesInterface)
{
Debug.LogWarning(self + " doesn't expose requested interface of type \"" + typeof(T) + "\".");
}
return (exposesInterface)
? self
: null;
}
///
/// Checks whether a implements an interface.
///
/// Interface type to check against.
/// .
/// if interface is exposed; otherwise.
public static bool ImplementsInterface(this Object self)
{
// Return early in case argument matches type.
if (self is T)
{
return true;
}
// Search in components in case object is a GameObject.
var gameObject = self as GameObject;
if (gameObject != null)
{
var components = gameObject.GetComponents();
return components.Length > 0;
}
// Return on fail.
return false;
}
}
}