- Home /
The question is answered, right answer was accepted
Making Inventory System Work for Multiple Food Types
I have a bomb inventory system implemented but right now I only have it working for 1 item (a piece of cake). How can I make this work for multiple types of food without copying and pasting my scripts over and over!
My script I put on the player:
public class InventoryItems : MonoBehaviour {
Foods foods;
public Inventory inventory;
Text text;
public int numOfCakes = 0;
public int cakeW = 1;
public int cakeS = 2;
void Awake()
{
numOfCakes = ES2.Load<int>("numOfCakes");
}
// Use this for initialization
void Start () {
foods = FindObjectOfType<Foods>();
text = FindObjectOfType<Text>();
}
// Update is called once per frame
void Update () {
}
private void OnTriggerStay(Collider other)
{
if (Input.GetKey(KeyCode.E))
{
if (other.tag == "Food")
{
if (foods.currentHungerPoints >= 1400
&& inventory.weight + cakeW < 30
&& inventory.size + cakeS < 40)
{
numOfCakes += 1;
inventory.weight += cakeW;
inventory.size += cakeS;
Destroy(other.gameObject);
}
else if (foods.currentHungerPoints + foods.cakeCal >= 1500
&& inventory.weight + cakeW > 30
&& inventory.size + cakeS < 40)
{
text.text = "Too heavy to carry!";
return;
}
else if (foods.currentHungerPoints + foods.cakeCal >= 1500
&& inventory.weight + cakeW < 30
&& inventory.size + cakeS > 40)
{
text.text = "Too bulky to carry!";
return;
}
else if (foods.currentHungerPoints + foods.cakeCal >= 1500
&& inventory.weight + cakeW > 30
&& inventory.size + cakeS > 40)
{
text.text = "Too bulky and heavy to carry!";
return;
}
}
}
}
void OnApplicationQuit()
{
ES2.Save(numOfCakes, "numOfCakes");
}
}
And my other script that I put on my Inventory canvas
public class Inventory : MonoBehaviour {
public Text text;
public Button button;
Foods foods;
InventoryItems inventoryItems;
public int weight;
public int size;
void Awake()
{
weight = ES2.Load<int>("weight");
size = ES2.Load<int>("size");
}
// Use this for initialization
void Start()
{
foods = FindObjectOfType<Foods>();
inventoryItems = FindObjectOfType<InventoryItems>();
Button btn = button.GetComponent<Button>();
button.onClick.AddListener(OnClick);
}
// Update is called once per frame
void Update()
{
text = FindObjectOfType<Text>();
text.text = "Inventory: Can carry 30kg/40L\n\n"
+ "\nCakes: " + inventoryItems.numOfCakes
+ "\n\nCurrent Weight: " + weight + "\nCurrent Size: " + size;
ES2.Save(weight, "weight");
ES2.Save(size, "size");
}
public void OnClick()
{
if (inventoryItems.numOfCakes > 0)
{
inventoryItems.numOfCakes -= 1;
weight -= inventoryItems.cakeW;
size -= inventoryItems.cakeS;
}
}
}
Answer by madks13 · Jul 05, 2018 at 01:20 PM
Can you post the Foods class? The obvious solution would be to have a base Food class, containing common food data, then inheriting that class by all the food types you need in your game. You should also have a list of the base food class, so you can know what kinds of food you have stored inside.