我有这个物品类:
public class Item
{
public string Name;
public Entity ItemOwner;
public Action<Entity> effect;
public Item(string name, Action<Entity> effect)
{
Name = name;
this.effect = effect;
}
public void Use()
{
effect(ItemOwner);
}
}
以及这个实体类:
public class Entity
{
public string Name;
public float Health;
public List<Item> Items = new List<Item>();
public bool CanDie;
public bool Dead;
public Entity(string name, float health, bool canDie)
{
Name = name;
Health = health;
CanDie = canDie;
}
public void UseItem(string name)
{
foreach (var item in Items)
{
if (item.Name == name)
{
item.Use();
Items.Remove(item);
break;
}
}
}
}
我想知道,当一个给定的实体放置在该实体的库存中时,是否可以将"EntityOwner"设置为该实体。
我目前能做的是这个"主程序":
Entity Player = new Entity("Dave", 50, true);
Item Potion = new Item("Healing Potion", ItemOwner => ItemOwner.Health += 25);
Potion.ItemOwner = Player;
Player.Items.Add(Potion);
Player.UseItem("Healing Potion");
我想要这个特定的代码:
Potion.ItemOwner = Player;
当物料放置在实体的库存中时触发。
这有可能吗?
我不认为这可以在item类中非常干净地实现
您可以在Entity
类中添加一个函数,如下所示:
public void AddItem(Item item) {
Items.Add(item);
item.EntityOwner = this;
}
类似地,您需要一个RemoveItem
函数来取消设置EntityOwner
。
如果您使用此方法,您可能希望Items
是protected
变量,这样在没有AddItem
函数的情况下,任何其他类都无法将项添加到列表中。
另一种选择是将OnAddedToList
函数添加到Item
类中,只需在该项上调用added to list函数即可代替上面的item.EntityOwner
。如果每件物品都有比设置所有者更独特的事情要做,这可能就是你想要的。