Переменная наследного класса в классе наследнике C# Unity
У меня есть классы:
public class Inventory : MonoBehaviour
{
string[] slots;
}
public class HumanInventory : Inventory
{
int selectedSlot;
}
public class Entity : MonoBehaviour
{
public Inventory inventory;
}
public class Human : Entity
{
public HumanInventory inventory;
}
Мне нужно, чтобы переменная inventory из класса Human заменила переменную из класса Entity.
Ответы (1 шт):
Автор решения: Егор Ясиновский
→ Ссылка
Вам нужно превратить ваши поля в свойства, и в наследнике заменить get и set. Сделать это можно так.
public class Entity : MonoBehaviour
{
private Inventory inventory;
public virtual Inventory Inventory
{
get
{
return inventory;
}
set
{
inventory = value;
}
}
public class Human : Entity
{
public HumanInventory humanInventory;
public override Inventory Inventory
{
get
{
return humanInventory;
}
set
{
humanInventory = value;
}
}
Так же послу получения Inventory из класса Human нужно будет привести его к HumanInventory. Например так
Human h = new Human();
int selSlot = (h.Inventory as HumanInventory).selectedSlot;