using System.Diagnostics.CodeAnalysis;
using UnityEngine;
namespace X10D.Unity;
///
/// Extension methods for .
///
public static class RaycastHitExtensions
{
///
/// Gets the component of the specified type from the object that was hit by the raycast.
///
/// The raycast hit.
/// The type of the component to retrieve.
///
/// The component of the specified type from the object that was hit by the raycast, or if no
/// component of the specified type was found.
///
public static T? GetComponent(this RaycastHit hit)
{
if (hit.transform == null)
{
return default;
}
return hit.transform.GetComponent();
}
///
/// Gets the component of the specified type from the object that was hit by the raycast.
///
/// The raycast hit.
/// The type of the component to retrieve.
///
/// The component of the specified type from the object that was hit by the raycast, or if no
/// component of the specified type was found.
///
/// is .
public static Component? GetComponent(this RaycastHit hit, Type componentType)
{
if (componentType is null)
{
throw new ArgumentNullException(nameof(componentType));
}
if (hit.transform == null)
{
return default;
}
return hit.transform.GetComponent(componentType);
}
///
/// Attempts to get the component of the specified type from the object that was hit by the raycast, and returns a value
/// that indicates whether the operation succeeded.
///
/// The raycast hit.
///
/// When this method returns, contains the component of the specified type from the object that was hit by the raycast, or
/// if no component of the specified type was found.
///
/// The type of the component to retrieve.
///
/// if the component of the specified type was found; otherwise, .
///
public static bool TryGetComponent(this RaycastHit hit, [NotNullWhen(true)] out T? component)
{
if (hit.transform == null)
{
component = default;
return false;
}
return hit.transform.TryGetComponent(out component);
}
///
/// Attempts to get the component of the specified type from the object that was hit by the raycast, and returns a value
/// that indicates whether the operation succeeded.
///
/// The raycast hit.
/// The type of the component to retrieve.
///
/// When this method returns, contains the component of the specified type from the object that was hit by the raycast, or
/// if no component of the specified type was found.
///
///
/// if the component of the specified type was found; otherwise, .
///
/// is .
public static bool TryGetComponent(this RaycastHit hit, Type componentType, [NotNullWhen(true)] out Component? component)
{
if (componentType is null)
{
throw new ArgumentNullException(nameof(componentType));
}
if (hit.transform == null)
{
component = default;
return false;
}
return hit.transform.TryGetComponent(componentType, out component);
}
}