繁体   English   中英

无法使用通用接口将子 class 保存在具有父 class 的变量的通用父变量中

[英]Can't save a child class from a generic parent in a variable with parent class using an interface as generic

我正在尝试制作一个库存系统,您可以在其中轻松添加新武器类型。 只需从 class ToolInformation 创建一个孩子并输入它需要使用的攻击系统。

但是我无法将子类( MeleeWeaponInformation<MeleeAttack> )保存在变量ToolInformation<IAttack>

有谁知道让这个想法发挥作用的方法?

错误:无法将类型“MeleeWeaponInformation”隐式转换为“ToolInformation”

通用 class

[CreateAssetMenu(fileName = "New tool", menuName = "ScriptableObjects/Tool")]
public class ToolInformation<T> : ItemInformation where T : IAttack
{
    public T GetComponent(GameObject gameObject)
    {
        return gameObject.GetComponent<T>();
    }
}

儿童 Class

[CreateAssetMenu(fileName = "New melee weapon", menuName = "ScriptableObjects/Melee weapon")]
public class MeleeWeaponInformation : ToolInformation<MeleeAttack>
{
}

试图将其保存在这样的变量中

ToolInformation<IAttack> tool = (MeleeWeaponInformation)inventory.items[i].information;
if (tool)
{
    selectedTool = tool;
    playerController.attack += selectedTool.GetComponent(playerController.gameObject).AttackCall;
}

你这样做:

ItemInformation item = new MeleeWeaponInformation();

并添加

public IAttack GetComponent(GameObject gameObject)

到项目信息。

[CreateAssetMenu(fileName = "New tool", menuName = "ScriptableObjects/Tool")]
public class ToolInformation<T> : ItemInformation where T : IAttack
{
    public T GetComponent(GameObject gameObject)
    {
        return gameObject.GetComponent<T>();
    }

    IAttack ItemInformation.GetComponent(GameObject gameObject)
        => GetComponent(GameObject gameObject);

}

我找到了一种不同的方法来获得我想要的相同结果,但感谢您的帮助。

我的解决方案:

[CreateAssetMenu(fileName = "New tool", menuName = "ScriptableObjects/Tool")]
public abstract class ToolInformation : ItemInformation
{
    public abstract IAttack EnableTool(GameObject gameObject);
}

[CreateAssetMenu(fileName = "New melee weapon", menuName = "ScriptableObjects/Melee weapon")]
public class MeleeWeaponInformation : ToolInformation
{
    []public float damage = 1;

    public override IAttack EnableTool(GameObject gameObject)
    {
        return gameObject.GetComponent<MeleeAttack>();
    }
}

ToolInformation tool = (MeleeWeaponInformation)inventory.items[i].information;
if (tool)
{
    Debug.LogError("Tool Selected");
    selectedTool = tool;
    playerController.attack += selectedTool.EnableTool(playerController.gameObject).AttackCall;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM