通过界面投射组件

时间:2019-05-09 15:21:11

标签: c# unity3d

我想创建一个通用函数来统一查找属于给定接口的组件。我可以在指定接口时做到这一点,但我需要能够以任何方式抽象它吗?

指定的版本

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 个答案:

答案 0 :(得分:2)

感谢@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);
                }
            }
        }