Приведение компонента через интерфейс - PullRequest
0 голосов
/ 09 мая 2019

Я хочу создать универсальную функцию для поиска компонентов, которые принадлежат данному интерфейсу в единстве. Я могу сделать это, когда я указываю интерфейс, но мне нужно уметь абстрагировать его, любым способом, которым я могу это сделать?

Указанная версия

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;
}

1 Ответ

2 голосов
/ 09 мая 2019

Спасибо @Rufus L!Он дал ответ:

        public static Component GetComponentOfType<T>(GameObject gameObject)
        {
            return gameObject.GetComponents<Component>().Where(c => c is T).FirstOrDefault();
        }

Использование:

        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);
                }
            }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...