[英]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.