[英]c# Unity Sharing Script with different instances
問題是我有一個土豆課,當我通過庫存使用它時,應該只用馬鈴薯,而不能使用馬鈴薯。 取而代之的是,它使游戲中的每個土豆都脫穎而出,有沒有辦法讓所有土豆都擁有自己的代碼實例呢?
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 ();
}
}
}
...這需要一個可編寫腳本的項目
存在您的“每個引用都是相同的”問題。
您需要:
Potato
對象,但是所有土豆堆棧都是ItemStack
的實例,其中包含對理想土豆的引用實例)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.