Unity INVENTORY: A Definitive Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
inventory toolbar full inventor UI stackable items and Slot selection you will learn all of that in this tutorial I've teamed up with Tamara to show you this inventory implementation in the building game be sure to visit her channel for the point-and-click building tutorial on the right you can see all chapters in this video for the first three I will rapidly build this UI with a great drag and drop system bottom toolbar and full inventory pop-up on button press if you'd like to skip directly to the coding part please go to Chapters 4 to 12 of this video you will learn how to spawn new objects in the inventory how to use them and we'll also spend a bit of time while implementing item stacking at the very end I will show you an integration of the system we'll be building with the real game build by Tamara let's start here is the empty Unity project I will firstly create a new image call it toolbar resize it and move it to the bottom of the scene to make sure it will always stay there here in the anchor presets select bottom center then let's create our first inventory slot create a new parent image call it inventory slot and resize it in my case 55 by 55 because both of our images are currently white let's change their Graphics to make them a bit more visible you can download all Graphics that I will be using in this video completely for free Link in the description perfect now when the inventory slot is ready let's create a prefab out of it next we need to create a grid of those inventory slots click on the toolbar game object and add a new component called grid layout group change cell size spacing and finally modify child alignment to Middle Center now if we duplicate inventory slot a few times you can see a nicely looking Toolbar to create a main inventor window all we need to do is to duplicate the toolbar object rename it to main inventory move it to the center of the scene and change its uncores to Middle Center of course having 7 slots in the main inventory is not enough so let's resize this box and add a few more inventory slots perfect my only issue right now is that when this main inventory screen will be shown players will be able to still interact with everything around this box in the game in other games what usually happens is that the whole background is being abstracted by the transparent black background let's do this create a new image and rename it to dark background now resize it to the full screen open Encore presets and click double stretch option while holding alt or option key that way we'll make sure that it will cover the whole screen no matter what the resolution is give it a black transparent color because this dark background should be behind everything you are related we've created so far let's move it to the top of the hierarchy lastly we can group dark background and the main inventory together just create an empty object call it main inventory group resize it to fill the entire screen the same way we did with the dark background and set both background and main inventory as children now Everything Will Change visibility depending on enabling or disabling only one game object next we need to add a button that will show us the main inventory I will create a new image and call it shown main inventory button then resize it to the same size as our inventory slots and move it right here don't forget about setting bottom center anchors let's change its graphic to the one I've prepared before perfect now we need to create a button out of it click add component and add button what we'd like to do is that when the player click this main inventory UI will be enabled and the inventory button will be disabled to do that click this small plus icon in on click event drag in main inventory group and select game object dot set active true similarly let's add this button itself but this time set active should be set as false let's hide main inventory on the scene and Run the game you can see that everything works as expected to hide the main inventory we'll do a very similar trick but for the dark background object add a new component column button and create events to disable main inventory group and show up our inventory Button as you can see now everything works as expected time to implement the last highly UI related thing drag and drop system in my latest Drag and Drop video I showed you exact steps on how to do it I will now quickly go through all of them once more firstly I create a new object inside of an inventory slot called inventory item I create a new script called the same in this script we Implement three interfaces related to dragging and start or end of the drug then create logic using this simple line of code that when an object is dragged it follows the mouse position at the time of the dragging we also need to disable imitrek as Target so that we'll be able to check if we have a slot to drop underneath remember to create a prefab out of it then to avoid weird layout issues I've created the logic that on drugstart the object is placed on top of everything and only on drop its parent is reverted because ondrop position does not revert to the center of the inventory slot we need to add a new grid component to align the object inside of it remember to update inventory slot Reverb after any changes time for dragging items between slots on the inventory slot prefab let's create a new script called the same inside of it I will Implement an eye drop Handler interface this method will check if any item is being dropped on the slot if yes let's check if this slot is not already occupied and change the parent of the dropped item so this is our final UI for now bottom toolbar main inventory on button press and the nicely working drag and drop system we'll now proceed to build a data structure for our items currently those Graphics are only set in the UI and the game wouldn't know if this is a building block or a tool is it stackable Etc to do that we'll create a new scriptable object in assets inside the script folder let's create an item script because stamara already created the exact same file I'll copy its content to our project let's go through it as a reminder a scriptable object is defined by replacing monobehavioral with the scriptable object interface it is also very useful to add this create asset menu attribute which you will see in action in just a second then here are variables tile will be used to show graphic on the map greed we won't be using that for now image will be pretty important to us it will be the Sprite shown in the inventory and type action type and range won't be used in the inventory itself but are very important for the gameplay mechanics they Define if the item is a building block or a tool if this tool digs or mines and finally in what range this tool can be used I myself will add one more variable that will be very important for our inventory public pool stackable which equals True by default this variable will be used to determine if this item should be stacked in the inventory just like in Minecraft some blocks can have multiple instances in one slot While others require you to have a separate slot for each one of them now when the item script is ready we can create some items in assets create items folder and then write click and select add scriptable object item let's create first item together we will give it a digging block name leave all gameplay related variables with defaults then in the stackable please leave true to enable Stacks in the inventory and finally assign the correct grass Sprite here are configurations for all other items we'll be creating today now time for the scripting part I'd like our inventory item to set its values based on the assigned scriptable object item in inventory item script let's create a field for that public item item and the method that will initialize our item public void initialize item with new item parameter inside let's type image.sprite equals new item dot image finally for the testing purposes I'll also create a start method that will initialize our item on the game start save go back to int and now on every item on the screen assign a different item object now after starting the game you can see that each item automatically loads its price of course we won't be assigning those scriptable objects manually but we'll do that using other scripts because of that in the inventory script we'll hide the item field from the inspector using this handy property from now on this variable will be used to save information about which item is tied to this game object another change will be to remove the start method and then modify initialize item a bit now this method will be an input point for our system to set up an item so what we need to do is to assign a new item to the item variable it will come handy later on now we can move on to create an inventory manager and control adding items to the inventory I will create a new empty game object and call it inventory manager then let's add a new script called the same and open it remove start and update and create a public method called add item it will take an item parameter then we can also create a spawn new item method with item and inventory slot parameters this first method will be called from the outside with the information what item should be added and item will search for any unoccupied slot in the inventory and when found it will call the spawn new item method with information about Which slot should be used and what kind of items spawned to search for unoccupied slots we firstly need to have an array that will gather all of them at the beginning of the Class Type public inventory slot and open and close square brackets to create array called inventory slots when I will now save the script you can see that we have a new field in unity inspector that should be filled with all inventory slots available in the UI because I want to firstly search for free slots in the toolbar I will start from them you can either drag each slot one by one but what would be a better option you can lock the inventory manager inspector select all remaining slots in the hierarchy and just drag them to the inventory slots array remember to unlock the inspector to avoid any confusion later on now when we have all slots assigned let's perform a search Logic in the add item script let's create a for Loop that will go over each element in the array I will also create a temporary variable that will store the slot in question to make things a bit easy and then do the check if if what exactly our goal is to get information if this slot currently has any item inside of it and you may remember that such an item always sits as a child of such a slot so what we can do is to create a new temporary variable called item in slot that will be assigned to slot dot get component in child type of inventory item that way we can now do the check if item in slot is equal to null which means that there isn't any item in that inventory slot if this slot is not occupied that means we can spawn our new item here type spawn new item and pass in the item argument and Slot variable that defines where we should spawn it finally type return to stop executing this code any further this video is brought to you by awesome color code Patron subscribers if you'd like to support free game development education and get access to these and many other tutorial source files check out the link below to join now let's quickly create a spawning logic so that we'll be able to test out everything in the game in spawn new item method type game object called new item game object equals instantiate which if you don't know that method creates a new game object on the scene with the past in inventory item prefab and information what will be its parent in our case inventory slot dot transform we are missing of course the prefab verbal let's quickly Define it at the top public game object inventory item prefab and quickly assign it to the previously created prefab in unity inspector then we also need to get an invest inventory item script that sits on that newly created game object type inventory item called inventory item equals new itemgameobject.getcomponent type of inventory item having access to this method we can now call inventory item dot initialize item and pass in the item that should be set up a small reminder that this method just assigns item variable and Sprite image based on the received input okay that was a lot of coding and we are very close to spawning new items but unfortunately we still do not have any way to spawn those items on this scene finally our game should send information to us saying hey add this item to the inventory but until then let's just create a demo script and a simple UI to simulate that here is a test group of three different buttons and an empty demo script let's open in it and create two variables public inventory manager inventory manager that will hold the reference to the manager and public array of item called items to pick up then one simple method public void pickup item with int ID parameter and then inventory manager dot add item with argument items to pick up ID save the script and in unity inspector assign inventory manager game object and a few items to pick up now for each of the three buttons add a new on click event drag in this demo game object select demo script pickup item and finally type different IDs starting from 0 to add different items guess what we can now finally preview all of the logic we've created so far start your unity game and click one of the buttons as you can see that immediately adds this item to the inventory and that works for multiple items as well also notice that when I'll move this first item to the back any new item will fill out the empty space first of course our main inventory works as well and spawns items if there is not enough space in the toolbar now here is the issue when I fill out the entire inventory and click the button nothing happens in our add item method we just check if there is any slot free there isn't so we just do nothing but imagine that in your game you collect something bad because inventory is full it disappears and you can't do anything with the collected item what we'll do in the script is that this method will return a true or false and based on that the game will know if the item has been successfully collected to do that replace void with bull here type return true which will mean that the item was added and here at the very end of this method add return false that will be triggered only if no freeze load has been found now we can go to the demo script and here let's add a variable that will hold information if the addition was success type bull result equals then we'll use this variable to send message to the console if result is equal to true then debug.log item added else any other message that will tell what's going on now you can see that while adding items we get messages about successful additions but when there is no space left we get a message item not added that logic will be especially helpful while integrating the game with the UI later on another thing you might have noticed is that currently items do not stuck with each other we like to build the same system as in Minecraft where there can be multiple instances of the same item and only when the max count is reached the second slot starts to be occupied let's do that firstly we need to prepare our inventory item to hold the information about the count here next to the item variable type public int count equals 1 that way by default each item will start with the one quantity then we also need to have a way to display such text let's add a text variable at the top called count text we might assign value to it here in setup item but I think it would be much better to create a separate method for that type public void refresh count and inside type count text that text equals count dot to string don't forget to call this refresh count in the initialize item method in unity open inventory item prefab and add a new UI text to it I will call it count resize it to fill the bottom part of the item change text to 1 change alignment to right and finally make this text bold the then in the inventory item script simply assign this newly created text you can see that now when I start the game each item has a number next to it I think it would be a good idea to hide this text if count equals one otherwise it looks a bit weird to do that we can go back to the inventory item script and here in the refresh count simply type bull text active equals count greater than one and then count text dot gameobject dot set active and pass in text active variable now the text is always hidden but if I add a random count just for fun you can see that everything works as expected now actually we only need one last thing to enable stacking here in the inventory manager while adding item we need to not only check empty slots but also find slots with the same item and count lower than maximum the best way to do that will be to just copy this bit of code paste it above change comment and modify this if statement we need to take three things first if there is any item in the slot so item in the slot is not equal to null then if item in slot is the same one we are searching for item in slot dot item is equal to item and third one if count of items is lower than a set number let's say for if all of that will be true that means we can change count of the existing item and update its UI so type item in slow dot count plus plus to increment it by 1 and item in slot dot refresh count to update the number on the screen and that's it just before going to UNT I will create this new public variable called Max stacked items and replace this hard-coded value now when I save the script and go back to Unity we can check our slots counting in action firstly I create one item and then each new one is stacked together I can only see this one issue that we forgot about checking if an item is stackable that's why this pickaxe doesn't behave as intended we can easily fix it by adding this check in the add item method we are slowly getting to to the end but there are two more things we need to talk about selectable slots and using the items in our inventory let's tackle the first one I want our slots in the toolbar to be selectable like in Minecraft that way we'll know which item should be placed or used in the game to give the player an idea which slot is selected we'll just change its image color like in this example let's make it quick in inventory slot I'll add three variables public image image you'll need using QT engine.ui for that it will be a reference to the slot image and two public color variables selected color and not selected color then down here let's add two public methods select and deselect as you might have guessed in select we'll change image color to selected color and in deselect we'll change it to the not selected color also in the awake method I will run the deselect method that way we'll make sure that at the start of the game all slots look like they are disabled great now in inventory manager let's create some logic to make this selection at the top I'll create a new variable called selected slot that will keep track of Which slot is currently selected by default it will be assigned to -1 which means that nothing is currently selected then let's create a new method called chain selected slot that will take end new value as the parameter as the name suggests this new variable will tell us Which slot will be the new one so let's use it right away type inventory Slots of ID new value dot select and then assign this selected slot variable we've created above to the new value but if a player changes their slot to any other one we should firstly disable the old one at the beginning of this method type inventory slots with ID of selected slot Dot deselect and because this -1 value does not exist in Array let's also check for that by typing if selected slot is greater or equal to zero in unity to test it out go to inventory slot prefab and assign its image and both colors please remember to set up the alpha value as well that way at the start of the game all slots will automatically get the not selected color thanks to the awake method we've created earlier if we'd like to select first slot automatically at the start of the game here in the inventory manager let's create a start method and type change selected slot with the parameter of zero perfect now at the start of the game we have the first result selected and the player can immediately see what's going on let's quickly give him or her ability to change the selected slot there are multiple ways you can implement it I will just use one to seven number keys on the keyboard to change selection in the inventory manager script let's create an update method here we can do it two ways the easiest one would be to create if or switch statement that will check if input.getkey done with the key code of alphanumeric one two seven then change selected slot 0 to 6. that works but this solution is not really elegant and looks a bit messy an alternative way would be to code it like this with this line we check if any key is pressed then check if the Press key is a number and finally only if the number is between our range we'll call the change selected slot method please go with the solution that you are more comfortable with time for the last coding challenge using items this one should be pretty straightforward some other script will ask inventory manager what item is in the currently selected slot our job is to return it properly and remove it from the inventory if needed in inventory manager create a new method called get selected item that will return item type then let's create a temporary variable that will tell us which is the currently selected slot just like in the add item method I'd like to also get information if this slot has an item inside of it and perform a check based on that so let's copy and paste this bit of code if item in slot is not null then let's return item in slot dot item otherwise return null just as I did with adding items I will create a new test button on the scene called get selected item and create a new method in the demo script with the same name to test out this functionality I need to type item received item equals inventory manager dot get selected item and then just to check what we received I will also type debug information after assigning the button to the correct script and launching the game you can see that when there is no item in the slot we get no item received message but when we add something and click this button again we get info about the selected item perfect of course there is still one last thing missing because when in the game you place an item or use it it should disappear from your inventory we can do that pretty easily here in the inventory manager in the get selected item method let's add a parameter bull use if that value is true it will mean that we should get rid of this item or at least decrease its count let's replace this return with assignment to new variable and then create an if statement that checks if use is equal to true if yes then let decrease our item count by one type item in slot dot count minus minus if that will mean that the item installed that count is lower or equal to zero then we need to destroy inventory item game object so destroy and passing item in slot Dot Game object if that is not true and this item still has some remaining qsys let's just simply use our refresh count method to update its UI and that's it I will only add a new test button called use selected item with the difference that this time true parameter will be passed that tells the inventory manager to use this item now run the finale let's test out everything we've built today start the game add some items notice how they are beautifully stacked we can then open our backpack drag items there spawn new items to fill out the empty space in the toolbar then change selected slot get info about what item is in the selected slot and finally use this item and either decrease its count or remove it completely perfect time for the very last part I want to show you this great project that Tamara created on her Channel where you can experience a terraria-like building system it allows you to place different kinds of blocks break them and even collect dropable items please go and watch her tutorial if you'd like to learn how to create all of that from scratch but there is something missing here oh much better as you can see I've imported all the UI scripts we've created today but no demo buttons they won't be needed anymore because we'll integrate that functionality into the game here is a checklist of all the things we need to modify in our scripts to make everything work let's start before we'll be able to break anything we need to get some tools in our game we'll get a pickaxe and shovel at the start of the gameplay to do that in the inventory manager script I'll add a new public variable called start items it will be an item array then in the start method we can create a loop for each item in start items simply and item now annuity in the inventory manager we just need to assign which items are generated at the start here it is but as you can see the game still doesn't know which item is Select so let's move on because a few different scripts will be using methods from inventory manager we need to make an instance of it that will be accessible from all scripts in inventory manager at the very top type public static inventory manager called instance and then in the awake method type instance equals this perfect that way we can now proceed with the first step in the building system script from Tamara here is an update method that checks all the time what is currently selected item for now this item is hard-coded so let's remove this variable and in the update method let's type item of a type item equals inventory manager that instance that get selected item and passing false as a reminder false here means that this item won't be removed in the inventory just yet and now when I run the game let's take a our pickaxe and break the stone Perfect The Next Step collecting items notice that when I move the character dropped items are collected but do not show up in the inventory that's an easy fix in loot script that is tied to all dropped items on the scene we need to perform some modifications with the collecting items here just before starting the cartoon type inventory manager that instance dot add item and passing item variable you might remember that this method actually returns true or false depending if there is free space in the inventory if there isn't we shouldn't be able to collect it to perform this logic and bull can add equals before the add item call and then add if statement that will start the core routine only if can add is true works perfectly Stacks all collected items in the inventory the very very last step to do is to enable building blocks actually you can already build them but building does not decrease their number in the building system script where we've been before scroll a bit down to the build method all we need to do here is to remove the selected item while placing the block type inventory manager that instance that get selected item with true to remove it from the UI and that's it ladies and gentlemen we can now Break Stuff build it break once again and if we'd like to we can also manage a full inventory that goes with it thank you so much for staying around till the end check out Tamara video my other tutorials and join amazing patterns that support this channel see you soon
Info
Channel: Coco Code
Views: 78,807
Rating: undefined out of 5
Keywords: unity inventory, coco code, cococode, coco code inventory, unity drag and drop, inventory, unity tutorial, Maciej Maj, bionicl, bionicl333, unity inventory slots, items, item stacking, Minecraft, Minecraft unity, Tamara Makes Games, Terraria, unity inventory system, unity inventory system tutorial, unity inventory tutorial
Id: oJAE6CbsQQA
Channel Id: undefined
Length: 35min 20sec (2120 seconds)
Published: Thu Sep 29 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.