Create Inventory and Crafting Systems in Unity

You can access the full course here: Create Reusable Crafting Systems in Unity

Part 1

In this course you will learn how to create an inventory and crafting system. The inventory will be your typical grid-based, slot, drag and drop style inventory system. The crafting system is going to be heavily influenced by Minecraft’s crafting system, with the nine slots in a grid, that you can drag and drop items into, and then it’ll do the recipe look-up to see if you have the items to craft up a new item.

We are going to take two approaches to this, we are going to have a system in place where you have to have the items in a specific slot in the crafting grid for it to work. Similar to the way Minecraft works where you have to have items in a certain order to craft certain items. We will also have it so you can actually just place items in the grid and it’s going to use the items just as a whole, and not care about the sequence of the items.

The first thing we need to do is create our item and recipe data structures. These are going to be classes that allow us to define what an item and a recipe is.

So, to get started with all this go ahead and create a new Unity project. You can name the project whatever you wish, but I will be naming mine “Zenva-Inventory and Crafting.” 

Unity 2017 2D project creation screen

Set it to a 2D project, and disable Unity Analytics.

Set your layout to default, so it matches the one I am using for this course.

Unity default layout option

We will begin by creating the folder structure for the project. We will need to create a new folder in the Assets folder and name this new folder to “Scripts” create a second folder and name this one “Resources.”

Now create a new folder inside the Resources folder you just created and name this folder to “Items.”

This all the folders that we will need for now.

We will begin creating our first script which will be the item data structure. So navigate to the Scripts folder and create a new c# script and name this script to “Item.” Open the Item script up in your code editor. See the code below and follow along:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Item {
    public int id;
    public string title;
    public string description;
    public Sprite icon;
    public Dictionary<string, int> stats = new Dictionary<string, int>();

    public Item(int id, string title, string description, Sprite icon, Dictionary<string, int> stats)
    {
        this.id = id;
        this.title = title;
        this.description = description;
        this.icon = icon;
        this.stats = stats;
    }

    public Item(Item item)
    {
        this.id = item.id;
        this.title = item.title;
        this.description = item.description;
        this.icon = item.icon;
        this.stats = item.stats;
    }
}

Save this script.

Part 2

In this lesson we are going to create the crafting recipe class, this class will define the blueprint for all of the recipes in our inventory system. The way that this is going to work is our recipes are going to be based on the item IDs, and then we are going to have an array of these IDs that defines what the recipe is. So if it requires two pieces of wood and a stone, and those are IDs one and two, respectively, then you would have an array that would have say, empty slots in it, they’ll just be ID of zero. You’ll have two that are one, and then one that is ID of two. That makes up the recipe that would craft whatever item that would make for you. Then whenever we put items into the crafting table it’ll look up the recipe and see if one matches what is in the crafting table.

So we are going to have nine slots in the crafting table so it’s going to be an array of nine items in the crafting table, each of those with an integer ID so we can compare those IDs in the crafting table to the recipes in our recipe database to see if we have any that matches what is in the crafting table.

So, a crafting recipe is an array of nine integers, and those integers represent the item IDs.

Create a new C# script in the Scripts folder and name it “CraftRecipe” this is going to be a class very similar to our item class. Open the CraftRecipe script in your code editor, see the code below and follow along:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CraftRecipe {
    public int[] requiredItems;
    public int itemToCraft;

    public CraftRecipe(int itemToCraft, int[] requiredItems)
    {
        this.requiredItems = requiredItems;
        this.itemToCraft = itemToCraft;
    }
}

Save the script.

Part 3

The code in the video for this particular section has been updated. Please see the information below for the corrected code.

In this lesson we will be creating the item database for our inventory system. We are going to define all the items in our system.

In the Scripts folder create a new C# script and name it “ItemDatabase” and open the script up in the code editor.

See the code below and follow along, The following code has been updated, and differs from the video:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemDatabase : MonoBehaviour {
    public List<Item> items = new List<Item>();

    void Awake()
    {
        BuildItemDatabase();
    }

    public Item GetItem(int id)
    {
        return items.Find(item => item.id == id);
    }

    public Item GetItem(string title)
    {
        return items.Find(item => item.title == title);
    }

    void BuildItemDatabase()
    {
        items = new List<Item>()
        {
            new Item(1, "Diamond Axe", "An axe made of diamond.", 
            new Dictionary<string, int> {
                { "Power", 15 },
                { "Defence", 7 }
            }),
            new Item(2, "Diamond Ore", "A shiny diamond.",
            new Dictionary<string, int> {
                { "Value", 2500 }
            }),
            new Item(3, "Iron Axe", "An axe made of iron.",
            new Dictionary<string, int> {
                { "Power", 8 },
                { "Defence", 10 }
            })
        };
    }
}

Save the script.

 

Transcript Part 1

Hey, guys. My name is Austin Gregory. And in this course I’m going to teach you how to create an inventory and a crafting system.

The inventory’s going to be your typical grid-based, slot, drag and drop style inventory system. And the crafting system is going to be heavily influenced by Minecraft’s crafting system. With the nine slots in a grid, that you can drag and drop items into. And then it’ll do the recipe look-up to see if you have the items to craft up a new item. And we’re gonna take two approaches to this. We’re gonna have a system in place where you have to have the items in a specific slot in the crafting grid for it to work. Similar to the way that Minecraft works, where you have to have items in a certain order to craft certain items. And we’re also gonna have it where you can actually just place items in the grid and it’s going to use the items just as a whole. Not care about the sequence of the items.

What I have in front of me is just a to-do list that we have to check off as we go here. And by the time we check off the last item, we will have a pretty sweet inventory and crafting system to work with. So the first thing we have to do is create our item and recipe data structures. And these are gonna be classes that allow us to define what an item and a recipe is. And we’re gonna talk about that here in just a second.

So, I have the window open for Unity to create a new project. I’m going to go to New. And I’m going to create a Unity project. It’s going to be Zenva – Inventory and Crafting. I’m going to select 2D. And I do not need analytics enabled for this. Does not matter how you do this for yours. And now I have my layout. That looks like this. This is how I work.

But I’m going to go to Layout. And I’m going to go to the Default layout, so we can all be working on the same layout. And we’ll go to Default and this is what you should see if you have the Default layout. Now we want to create a little bit of a folder structure here. I’m going to go to, I’m going to right-click on Assets. Going to go to Create. And I’m going to select Folder. And I want to have a couple of folders to keep my project semi-organized. I’m not so great at that myself. But we can do it a little bit better for this video, surely. So I’m going to have a folder for scripts. Then I’m going to right-click in here and go to Create again. And I’m going to have a folder for resources.

Now this is going to be where our item icons are. And our things that we have to load in dynamically are going to be stored in here. This is a special folder in Unity that allows us to access the data within it directly through a class called Resources. And we’ll get into that a bit later on. And also, speaking of the item icons, those are going to be available for you in the project download that you get. So in Resources I’m going to create a folder that’s going to be called Items. And that’s all we need for now.

So we said I want to create the Item data structure. So I’m going to do that in Scripts. It’s going to be a C# Script. So I wanna go to Create, C# Script. And I want to call it Item. And I’m going to open this up in Visual Studio by double clicking on that. And when you open it up, this is what you should see. We have some using statements up top here. Public class Item that inherits from MonoBehavior. Great. And we have some default methods.

So what I want to do is I’m going to set this up and then we’ll talk about. I want to get rid of the inheritance from MonoBehavior. Because this does not need to inherit from that. I’m going to get rid of that. And we’ll talk about what a class is, here in just a second for those of you that would like a refresher. And I’m going to go ahead and get rid of these methods. We’re not going to be using those for this.

We’re going to create all of our stuff ourself here. And this is what we have. A public class called Item, with two curly braces.

Cool. So quickly, what is a class? If you’re not familiar, a class is something that we can design that will act as a blueprint whenever we construct objects in the future. So think of a blueprint for building a building. You’re going to draw up all the specs for this. And then you’re going to hand it off to someone that’s going to follow the specs on that sheet. And build the building according to your specs. And it’s going to be the same thing for this class of Item. What we’re going to do is we’re going to write the specs for Item. And it’s not going to actually be an item. It’s just going to be the blueprint for an item. And then later on, we can construct our items based on this blueprint. And that’ll all make sense as we go.

So with that said, what does Item have to be? What is an Item? How can we define an Item? What an Item has to be in this system, at least, is it has to have a title, a name. Has to have a description. Some flavor text about it. Has to have an icon, we know that. Need an icon for this Item. Has to have a stat list, perhaps. So we can have some stats on our Items. Just a dictionary. Simple dictionary will cover that. As well as an integer that will be the identifier for it.

So I’ll go ahead and type these out. I want to have a public int id, the identifier for it. And these are going to be publicly accessible. So public int id. I’m then going to have a public string. And this is going to be the title. Now I’m calling it title instead of name, because by default objects already have a name field. And we do not want to have any conflicts with already existing fields, right? It’s very simple to just call it something else. In this case, title. If you want to call it anything else other than that, you, more than welcome to.

Then I can have a public string for the description. Now these are just strings of text. So title’s going to be a name. Description’s going to be a paragraph, or something like that. And then like I said, we’re going to have the icon. The icon is going to be, a Sprite. So I’m going to do a public Sprite. And I’m going to call it icon. Great. So we can assign a Sprite object to this Item. And that will represent the Item in the UI. Pretty cool. I also want to have, like I said, the stat list. Now we’re going to use a Dictionary for this. Because what we want to do is what you want to have a name of the stat, say power, or defense. Then we want to have the number that the stat is. The level the stat is, or the value the stat is.

So the Dictionary allows us to do that very easily by having a string key and then having an int for the value. So I can say power is 10. And defense is seven. And all that is within a single collection. Pretty cool. So to do that, we first have to make sure we have System.Collections.Generic because Dictionary is a Generic type. I’m then going to type again, public. And I want to type Dictionary. And I get this. And what this allows me to do with these two brackets here, the two angle brackets. It allows me to define the type that this Dictionary is going to be.

Hence, Generic, it doesn’t know the type until I define it. So I’m going to have string and then int. So string, is going to be the key. Int is going to be the value. So power 10, defense 20, so on. Pretty cool. Pretty simple. And the way we look it up is we just pass it the value of the name, so power. And it will return the value of the stat, so 10. Very easy. I’m going to call this stats. Then I’m going to initialize it, with new Dictionary.

Now the reason I’m doing this and the way this works is because this, if I were to define it, isn’t actually initializing it as the object of Dictionary. It’s just defining the field. Then later on I could initialize it and then add data to it. But I’m going to go ahead and initialize it here. And then later on I’m just going to send data to the constructor for this Item. And then it’s going to add that to the Dictionary. So now I’m using the new keyword here. That means I’m going to create a new object from Dictionary, using the Dictionary constructor. And that means it’s going to create simply a new Dictionary. And store it in the field of stats. Pretty cool. So now I have a stats Dictionary.

So I mentioned the constructor. We need a constructor for Item as well, because I want to be able to pass data to Item. And then assign that data to the id, title, description, icon, and the stats Dictionary. And the way that works is I have a blueprint with this, these fields in here, right? Id, title, description. And I can create a constructor that allows me to pass parameters to this object that I’m creating. And it will initialize the object with those values as the default.

If I were to do it without a constructor, and I just say new Item, kind of like I’m doing new Dictionary here. It will do the value. It’ll do the type default. So I’ll have, id would be zero. String would be empty. Description would be empty. And icon would be null. Because those are the defaults for those types. But instead, I want to initialize my Item with some values when I create it, right?

There’s no reason to create the Item in this case, unless it is an actual Item. So I want to have public Item. So I’m just saying public and then the name of the class. And that creates a constructor. And then inside the parenthesis we’re going to pass the parameters. We’re going to add the parameters that we can get into this Item. So I want to go to get the id, and we go int id. And I’m going to follow down the list here with the type and the name of the field. String title, string description, Sprite icon. And then, Dictionary. We’re going to do the same thing here. Dictionary and then it’s called stats.

Now, of course, these names do not have to match. It just makes it easier for me if they are the same. And then what I want to do is I want to assign those values to the values of the Item whenever we construct the Item. So if I were to go from another class and say new Item, like this. I could then pass in the values that I want this new Item to have. So, id of zero, name of Sword, and so on. And just pass the values. And then when this Item is created, when this object is initialized, it’ll have those values. Pretty cool.

So I have to initialize it with that. So I’m going to say this.id. This referring to the Item I’m creating. The instance of the Item I just created. And that’ll make sense whenever you actually construct the Item here in a moment. This.id = id; So this refers to the instance field. And this refers to the parameter I just passed in. So now this.title = title. And this.description = description, this.icon = icon. Now then we’re going to do this thing a bit different here with the icon. But I cannot do it yet, until I get them actually loaded into the game. So I’m going to just have it like that for now.

But later on when I’m going to come in and load the icon from the Resources folder, based on the icon, or based on the Item name. So in fact, we won’t need the Sprite.icon to be passed in to Item. All we need to do is have the name and then load the icon based on the Item’s name. And we’ll get to that here in a bit. And then this.stats = stats. I also want to create a constructor that’s going to act as a cloning constructor. And that would not be something we don’t, that’ll be something we need a bit later on. But I want to go ahead and create it while we’re in here.

And what a cloning constructor’s going to do, it’s going to take an Item of itself. So we have the class called Item. And I want to create a constructor that takes a parameter of Item and then just creates a copy of that Item. And the reason we do this, and you’ll understand this, again, later on.

But, I need to create a copy of an Item before I erase the reference to the Item. So I then have a hard copy of that Item. It’s a deeper copy of that Item, then I had before I made the changes to it. So all I have to do is I have to create a public Item. And it’s going to take a parameter of itself, of the self type. So it’s going to be Item called item. And this will probably be confusing for now. But you’ll understand later on exactly why we need this. And since I’m already in here, I want to go ahead and write it up. And I’m going to take and again, do this.id =. But this time, I’m going to do item.id, item being the parameter we passed in. Item has the field of id on it. It has the field of title on it. So we can grab those fields with that Item.

So whatever Item that I pass in to this Item constructor, I am then going to be cloning the information to a new Item. And this comes back to value versus reference type. Which I can’t really get into in this course. But you should probably check that out, if you’re confused as to why this works. This.title = item.title, this.description = item.description, this.icon = again I’m going to do item.icon for now. But I may have to load that in through the Resources. Well, I won’t because Item already have that. So that’ll be fine. And then, this.stats = item.stats.

So I’m just cloning the information over from Item to a new Item that I’m creating. And that’s going to be it for this lesson. In the next lesson, we’re going to create the recipe data structure. I’ll see ya there.

Transcript Part 2

Hey guys, welcome back. In this lesson we’re gonna create the crafting recipe class that’s going to define the blueprint for all of the recipes in our inventory system.

So the way this is going to work is our recipes are going to be based on the item IDs. And then we’re going to have an array of these IDs that defines what the recipe is. So if it requires two pieces of wood and a stone, and those are IDs one and two, respectively, then you would have an array that would have say, empty slots in it, they’ll just be ID of zero. You’ll have two that are one, and then one that is ID of two. And that makes up the recipe that would craft whatever item that would make for you. And then whenever we put items into the crafting table it’ll look up the recipe and see if one matches what is in the crafting table.

So we’re going to have nine slots in the crafting table so it’s gonna be an array of nine items in the crafting table, each of those with an integer ID so we can compare those IDs in the crafting table to the recipes in our recipe database to see if we have any that matches what is in the crafting table. So, a crafting recipe is an array of nine integers. And those integers represent the item IDs.

So to do that I’m going to create a C# script, I wanna call it “Recipe–” let’s say, “Craft recipe.” And this is gonna be a class very similar to our item class. I’m going to get rid of the monobehaviour inheritance again, don’t need any of that stuff. And as well as the methods. So, what is a craft recipe? Again, it’s going to have an integer array of nine item IDs, got that, makes sense. But also I have to know what this recipe will create whenever the recipe is satisfied. So whenever I have all of the items that this recipe requires what item do you get in return?

And since we’re basing the system on the item IDs, all I have to do is define the item ID of the item you get in return. And that’s all we need for the crafting recipe. So I’m gonna add a public integer that is an array and I will call it, “required item– required items” there we go. With a lower case r. And an integer here, just quickly, it’s an integer ID, you have the two square brackets following the type that denotes that it’s an array. And all this is, is a collection of this type. So I could have one value in here that’s zero or I can have ten values in here that’s zero, seven, eight, four, twenty, and so on. It’s just a collection of those values. And you can access those values by passing in the key or the index that the values at you’re looking for.

So if you want the third element in that array you would look for the, well you look, in this case, for the second key, because it starts at zero and goes zero, one, two, three, four, all the way up to nine, if you have ten elements. So the required items are gonna be an integer array that contains just a bunch or just a few item IDs. I then want to have a public Int that’s gonna be the item to craft. And this is simply gonna be an ID of the item you should get in return for passing in the required items. And again, all the craft recipe is doing is defining what a craft recipe is. It doesn’t handle any of the logic for determining if you have the required items in the table, it doesn’t care about any of that. It only cares about defining what a craft recipe is.

Now again, I wanna have a constructor for this. So a public craft recipe, just like the item. And the parameter we’re gonna be passing in is an integer item to craft. And then an integer that is an array. That is the required items. And then I’m going to set required items to be– sorry this.requireditems to be equal to requiredItems, and then this.ItemToCraft to be equal to itemToCraft.

Very simple, now we have a way to create a crafting recipe so whenever we create our crafting recipe database, all we have to do is create new instances of the class we just created and then define the values. So we’re going to use the blueprint to define the crafting recipe and we’re gonna follow the structure that we have here. We’re gonna pass in an array of the required item IDs. Then we’re gonna pass in the value of the integer, sorry of the ID of the item that you get back for passing in those.

And then some of the system is going to handle actually making that stuff happen. This just defines the blueprint for the craft recipe. And quickly for an example of the array, if you’re not familiar with how they work exactly, I have the required items array here that I just passed in, or the actual, I can refer to the instance required items. And I have values in this would say if it’s initialized with values, it’s not currently, but if we pass in values it will be. And I can access them with a key so two is zero, one, two, so it’s the third value in that array that would give me the third item ID that this recipe requires, or eight would give me the ninth ID that it requires.

So to check if we have the items for the recipe we would have to compare the item IDs that the crafting table has in it to all of the item IDs in this array. So we have nine in the crafting table, potentially, we have nine in the craft recipe, potentially. But more often than not, the recipes are gonna have a bunch of zero IDs in it, which are just no items, and then they’ll have other IDs, say you may need to make a diamond sword. So you have a wooden stick at the bottom, and then two diamonds on top. And that would make a wooden– or a diamond sword.

Or you would have just two diamonds in there somewhere with a wooden stick somewhere and that would still make it depending on what system you’re gonna be using because we’re going to be making both of those as I explained in the introduction. That is it for the craft recipe.

In the next lesson we’re going to create the item database where we define the actual items in our game, using the item blueprint we just created. I’ll see you there.

Transcript Part 3

In this lesson, we are gonna create the item database for our inventory system. We are going to define all the items in our system. I’m not going to have many, but I’m sure you’ll have a ton for yours, because you have an actual game going. I just have a little demo going.

So, I want to create some just dummy items to play around with, and show you how to construct a simple database of these items, and then the next lesson we’re going to create the recipe database in a very similar fashion. So I want to create, again, a C# script. I’m going to call it ‘item database’. I’m gonna open this up in Visual Studio. Oh, and I want to check off item structure and recipe Structure. There we go! So now this is where it starts to get fun. We start to have some fun with data here, and I know that doesn’t sound too exciting, but trust me, it is.

So to do that, we are going to create another generic collection similar to the dictionary, except it only has one value, it doesn’t have the key value pair, like the dictionary where we have the stat name and then the stat value, it just has a value of a certain type. So to do that I am gonna say ‘public’, and I’m going to create a list. This is a generic list so we have to have the angle brackets once more, and like we defined the two types for the dictionary, we have to define a single type for the list, and it will hold a list of this type. So if I had integer, we’d have a list of ones and tens and hundreds or whatever it may be, but in this case, we’re gonna have a list of a type that we created called ‘item’. Right?

So we have the item type here. It’s a class, and then it has these things in here that we can use, right? Pretty cool, so I want to have a list of those, and that’s gonna represent my item database. I’m gonna call it ‘items’, and again, I’m going to initialize it, like I did the dictionary. New list item–pretty cool. So now what I want to do, is I’m gonna get rid of these methods (computer chiming) once more, Don’t know what that was all about, and I’m going to write a method that allows us to build the item database.

It’s just gonna be where I define the values from our items at. Then I want to call it in the ‘awake’ or ‘start’ method, and it’s going to handle the rest. So, I want to write a void, which means it returns no value, so if you have an int method, it will return an integer. If you have an item method, it would return an item. But in this case, it returns nothing. It’s going to be ‘build item database’, is what we’ll call it. Needs no parameters, it’s just going to do something.

Now, I’m going to create a new item list, and I’m going to populate it with items, and we’re going to do this all in one statement, it’s going to be very cool, and I actually have a new list created here, but I’m going to create a new list down here, so it’s not necessary to have it here, but I’m going to keep it there for now. So, I’m going to type items is equal to, so items is the list, keep that in mind, this is the field that we created called public list item items, and I want to say it is equal to, again, new item, or sorry, new list, of type item.

But this time we are going to initialize it with some values, and the values we’re going to initialize it with is just a few items, right, so we’re going to create some items. To do that we’re going to use the curly braces, and we’re going to add a semicolon to the end. So your curly braces, everything inside of the curly braces whenever we define a new object like this, will define the values that it’s initialized with so we want to initialize the item database items list with some items in it, just makes sense. So to do that we’re gonna say ‘new item’. We’re going to use that item constructor by saying, ‘new’, which means it’s gonna create a new object, in this case a new item and then we can pass in to the constructor values to build that item using that blueprint. Watch how this comes together.

So new item, now if I go inside here and I want to do my parenthesis, I can see I can pass in an item type which is the clone constructor that we created or I can pass in an ID, title, description, icon and stats. Now, like I said before, we’re not gonna be passing in a sprite icon, we’re gonna be grabbing that from the Resources folder so I’ll have to change that for this to work.

I’m gonna pass in the ID of “1” for this, we’re gonna start at one instead of zero, because zero is going to represent an empty item, a null item, no item. So we can define our recipes using zero, meaning no item in that slot and one meaning that item or 20 being that item and so on, but zero means that slot is empty. Doesn’t require an item in that slot to craft, so we’re gonna start at one. Then also, the name of the item. We’ll make a diamond sword. Wants a description, well, a sword made of diamond. Very descriptive. Wants an icon, that is a sprite.

I’m gonna skip that for now even though I can’t do that legally, I’m gonna skip it for now and then remove it from the constructor here in a second. But it then wants a dictionary of stats. So in fact, what I’m then gonna do real quickly is I’m gonna go in here and I’m gonna remove this from the constructor. Because I’m not gonna be using in that way and then I am going to define my dictionary that is of stats.

So I’m gonna do this on a new line down here. It doesn’t matter what line we’re on as long as we are within the same statement and a statement is defined by the semicolon and the starting point. So semicolon here is where the statement ends, all this is within the same statement. So I’m gonna say ‘new dictionary’ because we’re passing in a parameter of a type dictionary, we have to create that dictionary first. And that’s gonna allow me to set it up here very easily by just saying, yeah, it’s a ‘string, int’ dictionary.

And then what I can do is I can define, much like I’m defining the ‘items new’ list item here with default values, with default initialized values. I can do that as well because I’m just creating it here and then I can pass in some values that the dictionary will hold when it’s initialized.

So to do that, again I’ll use the curly braces like we are for the items list constructor. And now within this it gets pretty cool here. What I can do is I can define a string value and then say the power being the string value and then 20 being the power level. So I’ll do that again in curly braces, and I’m going to have “quote” defining that this is a string, it’s gonna say, power and then comma, the value of power 15. So the diamond sword has a power stat of 15, very simple. And this is how we define the new item in our string and dictionary, the power is equal to 15. And I could define more, that’s the whole point of this, right, I can define as many as I want, so power is 15, we’ll say defense is seven, whatever it may be, up to you.

And you could do that for however many stats you have in your game and however you want to do that. And whenever you want to look up the value of the diamond sword, say the power stat, you would just go through, quickly I can show you here, say ‘items zero dot stats’, you could get the power level just like that and that will give you the power level in a string format, very simple. But I wanna have multiple items in my item database obviously so I’m gonna do that again kinda like I did with the power and defense here.

I have multiple items defined in the initializer for the dictionary. I could do the same thing for my items, so I wanna copy this and I’m gonna paste it. Notice the comma there, so I can add as many as I want now. And we’re gonna have this be ID “2”, you have to increment every time, and this is going to be a diamond ore. I’m just gonna say ‘a shiny diamond’. And maybe diamond ore doesn’t have a power or a defense stat, maybe it has a value stat. Maybe it’s worth a lot of money. Maybe it’s worth 2500 somethings, perhaps. And then again, I can add another item here that is of ID “3”, we’ll call it a steel sword. A sword made of steel.

Again, very descriptive descriptions and I can have again a power level of, this will be less than diamond sword ideally so it’ll be a power level of eight and it could have other stats as well. Again, however many you want, however you want to do this for your game, a defense stat. Maybe it has better defense than the diamond sword for some reason, I don’t know. Don’t know the lore behind diamond swords. And there you go, so now we have an item database at least with items defined. We don’t have anything that calls this method yet so it doesn’t actually happen but we have the meat of the database defined.

So now what I want to do is I want to make sure that whenever this object is initialized, whenever item database pops into the game, whenever the game starts, in my case because item database is always going to be there, I want to make sure ‘build item database’ gets called. The way I can do that is I can define a method, you notice when we started we had ‘start’ and ‘update’.

Well we could do start and that happens when the object is initialized but a bit before that happens the ‘awake’ method is called. And I want to make sure that this happens before anything tries to access it, this is data that needs to be initialized at the earliest possible state. So I want to say ‘awake’. So I want to create a method that is a void. It is private by default, I want to get rid of that anyway and it’s called ‘awake’ so now what I can do is say ‘build item database’ is called on ‘awake’.

So whenever this item first awakens, the first thing it’s gonna do is call it’s ‘awake’ method. The first thing it can do that we’re gonna be accessing is call it’s ‘awake method’ and then that’s gonna happen and it’s gonna call ‘build item database’ so now we have these items defined on our item database in our game.

Pretty cool– that’s no good on it’s own, we don’t have a way to go through and find a certain item that we’re looking for by the ID. Say we’re looking for ID of 15, well it would take us a bit of querying to get to that point to find that. So I want a simple method that I can call that I can pass it an ID and then it will return the item based on that ID. You can even do that by the item name or the item description, but I’m going to restrict it for now to the ID, to keep it simple. So, you know how I mentioned that ‘void’ means it returns nothing, then if you have a type there it returns that type of object, we’re gonna do that for this.

I’m gonna have a public method, we’re gonna be accessing it from elsewhere in our code. It’s gonna be a public method that returns a type of item and it’s gonna be called ‘get item’. Or ‘find item’ or ‘get item by this’ or whatever you want it to be. In my case, simply ‘get item’, it’s gonna take a parameter that is an integer ID so I can grab the ID of these items, find one that matches what I passed in here for the ID and then return that item. So how do we do that? There’s a ton of ways we can go about doing this. The best way for this course is to keep it very simple but also where we learn some.

So what I’m gonna do is I’m gonna loop through every item in the items database and in this case the items list and I’m gonna pass in a condition, if the item ID matches the ID I passed in, that’s the one I want, return that item. Luckily for us there is a built in way to do this on the items collection, so to do that I’m gonna say ‘items dot find’ and this is going to loop through, look at every single item in the items list and it’s going to compare it to a little query that we pass it. We’re gonna say, hey, I’m looking for this that equals this, if you find it, return that item to me and that I will pass it back to whatever called ‘get item’. So ‘items dot find’. This is where we have to define a predicate, which is why I just said we have to define a query.

So to do that I’m going to first use something that you have not have used up to this point, we’re going to use a lambda operator. So on the left side of the lambda operator you’re gonna have the input variable, which in our case is going to be a variable that will have the value of the item that we’re currently looped on top of. So if we’re looping over all the item in this and we get to the diamond sword here, whatever that we define on the left side of the lambda operator will be the member that contains that reference to that item.

So I’ll say, we can just say item, and then the lambda operator is on the left side, we have the input variable. Now on the right side we have the ‘expression’ and that’s gonna be what we are looking for, in a sense, the query that we are passing in. So I wanna check and see if the ‘item dot ID’ is equal to the ID that I just passed in. So item being the field, or sorry, the variable will be defined right here that will contain the item that we are looped on top of currently and once this happens it’s gonna then compare it to the ID we passed in for every single item but when it finds one it’s gonna be like, ‘okay, I found one’, then it’s going to give us that item back as a return value for ‘find’.

So then all I have to do is return that whole expression back out. And it’s gonna return the item, that define method found, to whatever called ‘get item’. — Very simple. Loop through every item, compare it’s ID to the ID we passed in, if it finds one, return that back to whatever happened, if it doesn’t find one, okay, no problem, so there we go. And you can see how easy this would be to actually do it for another value as well, so let’s say, ‘get item by string title’. Then we just do ‘item dot title’ and compare it to the title we just passed in. If it finds one, it will return it back just like this one does. And you can do it by any member on the item object. Member being a field on the item, in this case title, description, icon, ID and the stats list and that’s gonna be it for the item database.

In the next lesson, we’re going to create the recipe database, which is gonna be very similar to this except we have to write the ability to compare recipes to the items in our crafting table, we don’t have a crafting table panel yet, the window, the grid we don’t have that yet but we can easily work with just an empty array that will eventually be the items in the crafting table. And that’s going to be in the next lesson. I will see you there.

Interested in continuing? Check out the full Create Reusable Crafting Systems in Unity course, which is part of our Unity Game Development Mini-Degree.