- Home /
Need help with simple Crafting function.
I'm trying to make a basic crafting system for a simple game and i'm having trouble doing the following:
I have 2 classes one for the Item and one for the Recipe, I basically need to reference the Items needed to craft in the Recipe and output a GameObject.
But i'm having a hard time to figure out how to do this.
Basically, how do i reference the Item Ingredients in the Recipe and check for it in the Craft() function? So that i can then check if its Amount is enough to craft and then decrease it and other stuff needed?
Here is a example code:
[System.Serializable]
public class Item
{
public string itemName;
public int itemID; //This is used to keep track of this item and used for crafting.
public int itemAmount; //This is to know how many of this Item are in the game.
public GameObject itemObject; //This will be used as Output for the crafting.
}
[System.Serializable]
public class CraftingRecipe
{
public string recipeName;
public int recipeID;
public int recipeAmount; //The amount of the Item to output.
public GameObject recipeObject; //The output Object to be used in the scene.
}
public List<Item> items = new List<Item>();
public List<CraftingRecipe> recipes = new List<CraftingRecipe>();
public void Craft(int id)
{
//Craft the item.
}
Answer by sean244 · Jan 06, 2019 at 11:14 PM
What about this: First check if any of the items contains the id that is passed into the Craft function. If they do, then check if any of the recipes also contain that id. If they do, then check if the corresponding values match up.
public void Craft(int id)
{
foreach (var item in items)
{
if (item.itemID == id)
{
foreach (var recipe in recipes)
{
if (recipe.recipeID == id)
{
if (item.itemAmount == recipe.recipeAmount)
{
print("You have the right amount.");
}
}
}
}
}
}
Thanks this works as great, but how do i add more Items (from the Item class) as Ingredients for the recipe and check if i have the needed itemAmount of these Items?
Just add more conditional statements. You can do nested 'if statements' if you want
if (item.itemName == recipe.recipeName)
{
if (item.itemAmount == recipe.recipeAmount)
{
print("You have the right recipe.");
}
}
Add as many 'if statements' as you like :)
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is there a plugin for Visual Studio to find references to C# methods from Unity Events in scenes 0 Answers
How to fix my Life counter 1 Answer
,How to stop jump animtion 1 Answer