Я хочу создать универсальную функцию для поиска компонентов, которые принадлежат данному интерфейсу в единстве. Я могу сделать это, когда я указываю интерфейс, но мне нужно уметь абстрагировать его, любым способом, которым я могу это сделать?
Указанная версия
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;
}
Абстрактная версия
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;
}