Reputation: 21
I want to create a universal function for finding components that belong to a given interface in unity. I am able to do it when I specify the interface, but I need to be able to abstract it, any way I could do that?
The specified version
public static Component GetComponentOfTypeMovement(GameObject gameObject)
{
foreach (var component in gameObject.GetComponents<Component>()) //Go through each component on this character.
{
try //Attept something, and if it fails, goto catch.
{
var n_component = (IMovement)component; //Cast the current component as IMovement, if successful movementComponent will be set, and we can break from this loop.
return (Component)n_component; //Return the component if it has been found.
}
catch //If we have failed to do something, catch it here.
{
continue; //Simply keep checking the components, if we have reached this point, then the component we have attempted is not of type IMovement.
}
}
return null;
}
The abstract version
public static Component GetComponentOfType<T>(GameObject gameObject)
{
foreach (var component in gameObject.GetComponents<Component>()) //Go through each component on this character.
{
try //Attept something, and if it fails, goto catch.
{
var n_component = (T)component; //Cast the current component, if successful movementComponent will be set, and we can break from this loop.
return (Component)n_component; //Return the component if it has been found.
}
catch //If we have failed to do something, catch it here.
{
continue; //Simply keep checking the components, if we have reached this point, then the component we have attempted is not of the specified type.
}
}
return null;
}
Upvotes: 0
Views: 862
Reputation: 21
Thanks @Rufus L! He provided the answer, being:
public static Component GetComponentOfType<T>(GameObject gameObject)
{
return gameObject.GetComponents<Component>().Where(c => c is T).FirstOrDefault();
}
Usage:
private IMovement movementComponent
{
get //When we try to retrieve this value.
{
if (storedMovementComponent != null) //Check if this value has already been set.
{
return storedMovementComponent; //If the component does exist, return it.
}
else
{
return (IMovement)Utilities.GetComponentOfType<IMovement>(gameObject);
}
}
}
Upvotes: 2