【发布时间】:2018-06-17 00:57:33
【问题描述】:
问题是我有一个土豆类,当我通过库存使用它时,它应该使用土豆,而且只有那个土豆。取而代之的是,它从游戏中的每个土豆上取下它,有没有办法让所有土豆都有自己的代码实例?
public class Food : Item {
public float healthHealedOnUse;
public int uses;
}//name ect is in the Item base class
我用于库存的代码:
public void UseItem(){
if (item != null) {
if (item is Food) {
Debug.Log ("using "+item.name);
PHH.Heal (((Food)item).healthHealedOnUse);
((Food)item).uses--;
if(((Food)item).uses < 1){
ClearSlot();
}
} else {
item.Use ();
}
它影响了所有的土豆,而不仅仅是我点击的那个。
添加到库存
public List<Item> items = new List<Item>();
public bool add(Item item){
if (items.Count >= space) {
Debug.Log ("Inventory Full");
return false;
} else {
items.Add (item);
onItemChangedCallback.Invoke ();
return true;
}
}
玩家拾取物品脚本
void PickUp(){
Debug.Log ("Picking up " + item.name+"!");
bool wasPickedUp = Inventory.instance.add (item);
//Debug.Log(wasPickedUp);
if (wasPickedUp == true) {
Destroy (gameObject);
}
代码添加物品到库存槽
public void AddItem(Item newItem){
item = newItem;
icon.sprite = item.icon;
icon.enabled = true;
removeButton.interactable = true;
}
我如何在库存槽中显示物品
Inventory inventory;
public GameObject Inventoryui;
public Transform itemsParent;
InventorySlot[] slots;
void Start () {
Inventoryui.SetActive (false);
inventory = Inventory.instance;
inventory.onItemChangedCallback += UpdateUI;
slots = itemsParent.GetComponentsInChildren<InventorySlot> ();
}
public void ToggleInventory(){
Inventoryui.SetActive (!Inventoryui.activeSelf);
}
void UpdateUI(){
Debug.Log ("Updating UI");
for (int i = 0; i < slots.Length; i++) {
if (i < inventory.items.Count) {
slots [i].AddItem (inventory.items [i]);
} else {
slots [i].ClearSlot ();
}
}
}
【问题讨论】:
-
我们需要查看更多代码。您如何将物品添加到库存中?
-
另外,你应该让你的
Food类的Use()方法治疗玩家。这就是子类化的重点:Item#Use被标记为virtual,然后Food#Use被标记为override,你可以让UseItem()调用item.Use(),完成。 -
你去吧,我在那里添加了additem
-
关于食物的使用类,我认为这会比必须找到播放器组件,然后从播放器中获取播放器统计处理程序更好。
-
我把它变成了你的other问题的答案。关于这个……我现在需要知道你从哪里打电话给
add:也就是说,我需要看看你是如何将多个土豆放入你的库存中的。很可能你正在做类似var POTATO = new Food(); /*...*/ Player.inventory.add(POTATO);的事情,导致你所有的库存项目都引用同一个对象。