Quantcast
Channel: Latest Questions on Unity Answers
Viewing all articles
Browse latest Browse all 171066

Help making premade Items for farming game

$
0
0
Hi, I've been trying to make items for my farming simulation game (such as seeds, tools etc) but I've hit a snag when trying to make pre-made items the player can get. Originally, the Item class inherited from MonoBehaviour and attached to prefabs, which I could then drag into the Inventory class in the inspector of whatever would contain the item (e.g. a shop). However, I ran into problems creating a new instance of the object (MonoBevahiour doesn't like using 'new Item()') and copying the prefab would create problems with the 'amount' variable, where every item copied from the same prefab would have the same value for amount. Uninheriting Monobehaviour from the Item class allows me to create a new Instance of the Item class, but I can no longer attach the Item class to a prefab. Is there a way I can create a list of Items, which could then be assigned in the Inventory of whatever would have the Item? Or is there a way I can make a new Instance of a prefab (Item class inheriting from MonoBehaviour), with each copy of an item being independent to another. The classes I am using are below. class Item //Item Class { var ID : int; var price : int; var stackability : int; var image : Texture2D; var amount : int = 1; var selected : boolean = false; var worldObject : GameObject; function PassItem(newItem : Item) { price = newItem.price; stackability = newItem.stackability; image = newItem.image; worldObject = newItem.worldObject; selected = false; } } //Inventory Class import System.Collections.Generic; var inventoryItems : Item[]; var size : int; function Awake() { if (size != 0) inventoryItems = new Array(size); } function AddItem(newItem : Item) : boolean { if (CheckItem(newItem)) return true; else if (inventoryItems.Count == size) return false; else { for (var i = 0; i < inventoryItems.length; i++) { if( inventoryItems[i] == null ) { var item = new Item(); item.PassItem(newItem); inventoryItems[i] = item; inventoryItems[i].amount = 1; return true; } } } return false; } function CheckItem(desiredObject : Item) { for (var i = 0; i < inventoryItems.length; i++) { if (inventoryItems[i] != null) { if (inventoryItems[i].ID == desiredObject.ID) { if(inventoryItems[i].amount < desiredObject.stackability) { inventoryItems[i].amount += 1; return true; } } } if (i == inventoryItems.length - 1) return false; } return false; }

Viewing all articles
Browse latest Browse all 171066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>