It would be useful for, say, raycasting.
// Current method:
if (Physics.Raycast(ray, out RaycastHit hit, 1f))
{
Player player = hit.transform.GetComponent<Player>();
if (player)
{
// ...
}
}
// Or, using pattern matching:
if (Physics.Raycast(ray, out RaycastHit hit, 1f))
{
if (hit.transform.GetComponent<Player>() is Player player)
{
// ...
}
}
// Proposed, a more elegant alternative to pattern matching:
if (Physics.Raycast(ray, out RaycastHit hit, 1f))
{
if (hit.transform.GetComponent(out Player player))
{
// ...
}
}
// Like most such things, this can be easily extracted into an extension method, but would be nice to have officially:
public bool GetComponent<T>(this Component component, out T t)
{
T foundComponent = component.GetComponent<T>();
t = foundComponent;
return foundComponent; // This should work, since you can do `if (component)`. If not, cast?
}