using System;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using UnityEngine;
namespace Omega.Tools
{
public static class GameObjectUtility
{
///
/// Возвращает компонент, прикрепленный к объекту. Если экземпляр компонента заданного типа отсутствует на объекте
/// то он будет добавлен к объекту.
///
/// Игровой объект
/// Тип компонента
/// Экземпляр компонента
/// Параметр > указывает на null
/// Параметр > указывает на уничтоженный объект
[NotNull]
public static T MissingComponent([NotNull] GameObject gameObject) where T : Component
{
if (ReferenceEquals(gameObject, null))
throw new ArgumentNullException(nameof(gameObject));
if (!gameObject)
throw new MissingReferenceException(nameof(gameObject));
return MissingComponentWithoutChecks(gameObject);
}
///
/// Возвращает компонент, прикрепленный к объекту. Если экземпляр компонента заданного типа отсутствует на объекте
/// то он будет добавлен к объекту.
///
/// Игровой объект
/// Объект-тип компонента
/// Экземпляр компонента
///
/// Один из переданных параметров указывает на null
/// указывает на тип который не унаследован от типа UnityEngine.Component
[NotNull]
public static Component MissingComponent([NotNull] GameObject gameObject, [NotNull] Type componentType)
{
if (ReferenceEquals(gameObject, null))
throw new ArgumentNullException(nameof(gameObject));
if (!gameObject)
throw new MissingReferenceException(nameof(gameObject));
if (componentType == null)
throw new ArgumentNullException(nameof(componentType));
if (!componentType.IsSubclassOf(typeof(Component)))
//В качестве параметра componentType был задан тип не унаследованный от UnityEngine.Component
throw new ArgumentException(
$"As a {nameof(componentType)} parameter, a type not inherited from {typeof(Component).FullName} was set");
return MissingComponentWithoutChecks(gameObject, componentType);
}
///
/// Пытается найти объект на компоненте, если компонент найден вернет true а >будет указывать на найденный объект,
/// в противном случае, вернет false, а >будет указывать на null
///
/// Игровой объект
/// Ссылка на найденный объект (null, если объект не найден)
/// Тип компонента
/// true - компонент найден, false - объект не найден
/// Параметр > указывает на null
/// Параметр > указывает на уничтоженный объект
public static bool TryGetComponent([NotNull] GameObject gameObject, [CanBeNull] out T component)
where T : Component
{
if (ReferenceEquals(gameObject, null))
throw new ArgumentNullException(nameof(gameObject));
if (!gameObject)
throw new MissingReferenceException(nameof(gameObject));
return TryGetComponentWithoutChecks(gameObject, out component);
}
///
/// Проверяет содержит ли объект компонент заданного типа
///
/// Игровой объект
/// Тип компонента
/// true - компонент с заданном типом присутствует на объекте, иначе false
/// Параметр >указывает на null
/// Параметр >указывает на уничтоженный объект
public static bool ContainsComponent([NotNull] GameObject gameObject) where T : Component
{
if (ReferenceEquals(gameObject, null))
throw new ArgumentNullException(nameof(gameObject));
if (!gameObject)
throw new MissingReferenceException(nameof(gameObject));
return ContainsComponentWithoutChecks(gameObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static T MissingComponentWithoutChecks(GameObject gameObject) where T : Component
=> gameObject.GetComponent() ?? gameObject.AddComponent();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[NotNull]
internal static Component MissingComponentWithoutChecks([NotNull] GameObject gameObject,
[NotNull] Type componentType)
=> gameObject.GetComponent(componentType) ?? gameObject.AddComponent(componentType);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool TryGetComponentWithoutChecks([NotNull] GameObject gameObject,
[CanBeNull] out T component)
where T : Component
// Проверка на null выбрана намеренно, так как GetComponent никогда не вернет уничтоженный объект
// https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
=> (component = gameObject.GetComponent()) != null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool TryGetComponentWithoutChecks([NotNull] GameObject gameObject, [NotNull] Type componentType,
[CanBeNull] out Component component)
// Проверка на null выбрана намеренно, так как GetComponent никогда не вернет уничтоженный объект
// https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
=> (component = gameObject.GetComponent(componentType)) != null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool ContainsComponentWithoutChecks([NotNull] GameObject gameObject) where T : Component
// Проверка на null выбрана намеренно, так как GetComponent никогда не вернет уничтоженный объект
// https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
=> gameObject.GetComponent() != null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool ContainsComponentWithoutChecks([NotNull] GameObject gameObject,
[NotNull] Type componentType)
// Проверка на null выбрана намеренно, так как GetComponent никогда не вернет уничтоженный объект
// https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
=> gameObject.GetComponent(componentType) != null;
}
}