Crafting System

Hello Everyone,

Past few days I’ve been messing around with a Crafting system, I have a nice GUI set up were picked up items show in a inventory and then the GUI icon can be dragged to a ‘crafting’ GUI window and then crafted. I have managed to get the crafting sort of working.

The system I have at the moment uses an array system (still learning about array’s) and to build an item only requires one of a certain item say one plank & one iron. Is there a method that i’m not aware of that I can say ‘ok to make this you need X amount of this and this’?

Yes there is,

Now I’m not familiar with your implementation of your item/inventory system, but what you could do is loop through your array of items to be crafted and count how many of each item you have, and use that to decide whether the requirements for the outcome are met.

To give you a concrete example method:

Note this method is not the most efficient by far, but it is (hopefully) clear how it works:

    public const string boatCost = "PlankPlankIron";

    /// <summary>
    /// Can the cost be paid given the items?
    /// </summary>
    /// <param name="cost"> A coststring, could look like "AppleAppleSugar"</param>
    /// <param name="items"> Array of the items in the craft window</param>
    /// <returns></returns>
    public bool CostMet(string cost, Item[] items)
    {
        //Lets make a local copy so we don't mess with the original.
        string costString = System.String.Copy(cost);

        //Loop through all the items in the craft window.
        foreach (Item item in items)
        {
            //The cost for the item to be crafted includes (at least one) of the item we are currently looking at.
            if (costString.Contains(item.ItemName))
            {
                //Remove that from the costString.
                costString = costString.Remove(costString.IndexOf(item.ItemName), item.ItemName.Length);
            }
        }

        if (costString.Length == 0)
        {
            return true;
        }
        return false;

    }

    /// <summary>
    /// Check whether or not we can build a boat given with the items in the array.
    /// </summary>
    /// <param name="items"> Items in craft window </param>
    /// <returns></returns>
    public bool CanIBuildABoat(Item[] items)
    {
        if (CostMet(boatCost, items))
        {
            Debug.Log("Yes, I can build a boat given these items!");
            return true;
        }
        return false;
    }

In this example every Item has an ItemName property that is a string (name of the item).