Grid Inventory in Unity Tutorial Tile based inventory in Unity
Вставка
- Опубліковано 14 лип 2024
- Assets: drive.google.com/file/d/1TX8Y...
0:00 - Intro
1:07 - Grid Setup
4:30 - Item Grid
18:28 - Storing Items on grid
30:10 - Click to pick up item and move item
35:21 - Visualize of item drag
37:41 - Item size and item scriptable object
51:06 - Item occupy multiple tiles
56:40 - Item out of bounds check
1:03:15 - Handling Overlapping objects
1:15:47 - Object highlight
1:40:17 - Multiple inventory grids
1:41:41 - Insert item Add item to inventory
1:51:46 - Rotating item
2:00:07 - Addendum
In this episode of unity tutorial, me Greg will be making a grid inventory. Just like in games like Escape From Tarkov, Diablo or Path of Exile. This is tutorial how to make grid inventory in unity. How to make grid inventory from Path of Exile. How to make Grid inventory like in Diablo. How to make inventory like in Escape from Tarkov. Inventory from EFT how to make in unity. How to make in unity Grid inventory. Tile inventory in unity. How to make Tile inventory in unity tutorial.
Patreon: www.patreon.com/user?u=28674164
Ko-fi: ko-fi.com/gregdevstuff
Twitter: / gregdevstuff1
Discord: / discord
CORRECTIONS AND COMMENTS (will be added in course of discovering mistakes and errors) (If you stuck join discord or comment!)
This system is designed to be used with fixed resolution! Make sure you set the fixed resolution in the GameWindow and on the canvas.
25:46 instead of gridSizeWidth and gridSizeHeight, you need to use tileSizeHeight and tileSizeWidth! On 29:25 you can see correct code for this part!
Sorry for very sloppy editing in this episode, my computer can't handle videos of this size. So there is a lot of small misstypos being left because it was very hard to edit anything in this tutorial.
i didint see this and i was going crazy
Even if a change to tileSizeHeight and tileSizeWidth, the item is instantiated in the position 4 -4 with scale 1.45.
The only way a figure to fix was change this piece "position.y = - (posY * tileSizeHeigh + tileSizeHeigh / 2);" to this "position.y = - (posY * tileSizeHeigh / 2);"
I think I missed something in video, but anyway. On section "Item size and item scriptable object" I couldn't place created item because tileGrid could not be spotted (behind created item) because in Item prefab you should turn off 'Raycast Target'.
@@star_c4313 You definitely mised that part, but good job figuring it out! :)
An amazing job with this tutorial! Most tutorials out there are confusing and skip over some details, but you went in depth. Thank you very much!!!
An amazing tutorial! Easy to follow, in detail, good explanations. You saved me a lot of time, sweat and tears.
Wonderful tutorial!! For anyone wondering, if you rotate the item without moving the mouse, the highlight might not rotate at first. You can fix it by replacing "if(oldPosition == positionOnGrid)" with "if(oldPosition == positionOnGrid && !Input.GetKeyDown(KeyCode.R))" or whatever key you assigned to rotation in HandleHighlight().
I see a lot of questions regarding the UI scaling via a CanvasScaler. There's an easy solution to this. In ItemGrid's GetGridPosition(), you need to adjust the tileGridPosition x/y by the root canvas' scale factor. Adjust these two lines (rootCanvas is set to the root Canvas with the CanvasScaler component):
tileGridPosition.x = (int)(positionOnTheGrid.x / (tileSizeWidth * rootCanvas.scaleFactor));
tileGridPosition.y = (int)(positionOnTheGrid.y / (tileSizeHeight * rootCanvas.scaleFactor));
Great video!
But how do you scale the Icons?
MAH MAN i was looking for over 3 Hours to solve this and then went back to the comments here to find your comment. Thanks for saving my sanity tho XD
@@jellomello2683 Glad it helped!
@@niklasschiedeck same way, icon rectTransform localScale multiply by rootCanvas.scaleFactor
It took me about 3 weeks on and off ( maybe 15-20 hours total) to implement this with changes I desired as I went. I learned a lot.
Thanks so much for making this tutorial man!
This tutorial that you created is well-explained and easy to follow.
Thank you for providing this to the public, it's extremely helpful!
Thankyou so so much you saved me so much time and suffering trying to find this you defiantly deserve more recognition
Have you finished the video? If yes any feedback?
This is an incredible tutorial! It's elusively simple and really well coded all things considered. I've always wanted to make a grid inventory system but had no clue how to even start and this made it look really easy! You're a blessing to the indie game development scene!
Thank you. If you want to help, please spread the word around on social media! Consider checking my other tutorials.
Seriously a great way to do the Turorial everything step by step and easy to understand I learned a lot during ur Video and I am truly grateful for it.
best part is at 28:15 when he just said: "Ha????". I couldn't stop laughing, it was so unexpected, and expected at the same time. Great Video regardless. Keep the good work up!
Ha?????????
Amazing tutorial! After searching for a while this was exactly what I needed to help me get started with this system. It's very easy to extend it after you finish your tutorial to fit your games needs. Thank you so much!
Love you! Check the stream if you have time! And other tutorials! Post online so people will learn about this!
Incredible detailed & well made video. I followed the whole tutorial and everything worked.
Great job and a very good foundation!
Thank you!
Greate tutorial! I am happy I followed it because I am a novice at Unity and it helped me greatly!
Thank you. Join discord, and check pinned comments in help it have expansion for this system.
Amazing video. Thank you for taking the time to make something so detailed.
One of the best tutorials i have followed along with online. I learned so much from how you do things, keep up the great work. I will be checking out more!
Love you! UwU
This tutorial was so good i didn't wanted it to end! I noticed there's not much info about setting up inventories like SCUM, Escape from Tarkov, etc. so I hope to learn more tricks to replicate them.
Thank you so much!
Spread the word about the channel my dude! :)
Amazing tutorial, sets up a solid foundation for a project and everything is explained in detail. Although the content is difficult, you explain it so well that the video is easily digestible for a beginner like me .Thank you so much for providing this content for free and for giving an example of what a prefect tutorial looks like !!
I wouldn't call it perfect. There is some concepts left unexplored, and some systems are actually can be done way better. Thou it should provide you with foundation you can expand upon! :)
@Greg Dev Stuff I really enjoyed you showing everything you do, I found myself doing a lot less troubleshooting in your tutorial than I usually do in other tutorials, so thanks for that, looking forward for new tutorials :D
Thank you so much for this tutorial, it's gonna be a great help for my first game!
This is one really amazing tutorial. Much better than most of other tutorials that just copy paste 200 lines of code and explain nothing.
Thank you
Thanks for this, exactly what I needed. I tried using some GitHub frameworks for setting up a grid inventory, but found modifying them through their countless interface methods was more trouble than it was worth. Now I set up this grid, and I know exactly how it works so I can change it how I want.
Love the accent, 'Good' !
Good :)
I love it, really good from the start to the end, thanks you man !
Glad you liked it!
Amazing tutorial. I love you
Thank you very much for this tutorial! Everything is very clear and without confusion
Check my Discord channel in help pinned message on how to expand and improve the system to work with scalable UI
Amazing video. This tutorial is very helpful. Thank for your work :3. Respect from Vietnam
Very good video! Thank you a lot for your work and explanation :)
If you want the itemToInsert to check if it can fit rotated, you can just copy this under the CheckAvailableSpace:
if(CheckAvailableSpace(x,y,itemToInsert.Height,itemToInsert.Width)){
itemToInsert.Rotate();
return new Vector2Int(x,y);
}
It will cost more performance but depending on the inventory size you are going for it should do the trick. ^^
If you can't place item after creating it with Q make sure you disable raycast target on the item prefab Image component
thanks, I thought I did that already but I guess not
Thanks a lots
Liked, Subscribed, and Belled for good measure. Excellent tutorial.
Super nice tutorial, thanks for the explanations!
Thank you for watching! Check my other series i have a lot of stuff!
Right from the start perfect tutorial. Thanks
Join discord, there is a fix for resolution problem, in pinned messages.
Superbly explained
Check discord there is some expansions and optimization to the grid system!
Huge thanks, I learned a lot
Awesome tutorial, if you are in doubt and have been searching for a good inventory tutorial for a while, look no further.
Thank you :)
Very useful tutorial, thank you so much!
Glad it was helpful!
@@GregDevStuff How about Grid Inventory part TWO ? Ideas:
* Drop items to the floor.
* Items in steck.
* Window with a description.
* Item interaction (e.g. load weapons, unload weapons by dragging ammo in the inventory)
* Button 'Grab all' from chest.
* Different inventory for different characters
* Accounting for the weight of items.
Thanks!
thank you fork your kindness. I really like this video.
Thank you too!
Good job bro! This is definitely a like.
From myself I added to the Rotate method: if(itemData.width == itemData.height) { return; } So that an object with the same size does not rotate :)
Good idea! :)
Очень классная реализации, я когда то делал инвентаря на IMGUI (без вращения), поймал такие флешбеки))
Нашел єто видио, захотелось уже на юнити UI сделать)
поворота предмета - так не хватает многим grid base инвентарям, во общим заразили вы меня идеей повторного написания)) Однозначно лайк!
Без проблем!)
Do it, I am. You can't let the Americans beat you!
Nice job bro!
best tutorial ever
Awesome video bro!
THANK YOU! :)
Feels so hard to convert it into the new input system - thanks a ton for making this video though. This is great!
any luck? I'm having issues with the OnPointerEnter events not firing, unsure if IPointerEventHandler doesn't work with the new system or if something else is interfering.
Красавчик, брат, спасибо =)
Very good!
tnx you save my life
Thank you, bro
Gosh this video helped me out a tonne, I was trying so many other methods to make this work. how you would recommend about creating a save and load function and nesting inventories. Honestly your work needs to be appreciated more.
JSON or XML for the save load.
Nesting inventories should work out of box, you simply have to enable/disable them when needed.
You can help by spreading the word about the channel around social media and the friends. Thank you for kind words.
guess whos getting a shoutout on the credits of my game! its you!!!
THANKYOU! :) Good with the game. Remember to join discord we have showcase channel.
lifesaver
This was excellent tutorial as someone who was new to unity it went a bit fast at times but I assume this is angled towards more experienced peoples. Would you follow up by going from inventory to the ground and back?
Would it be possible to save the Inventory (the class that stores the references for the InventoryItems) as a Scriptable Object aswell to have it available in multiple scenes?
Hi there! Awesome tutorial, very informative! I do have a few question however: What would be the best way to make a "loot chest" with your system? As in having a randomly generated grid with item in it that changes everytime the project is ran. Also is there a way for you to move the grid around during runtime? Currently if I try to move the grid during runtime all the items no longer works.
1st you need to create an actual data structure for items. Right now at best this is just an framework/visual representation. Which bares no actual functionality on its own.
To deal with chests, it should be easy to simply use 1 grid which you resize when needed(be calling Init with the size of the container). If push to optimization come, you can pregenerate array of bigger size, and limit it based on opened chest.
I think it should be working fine if you move it aorund at run time, but even if it was working, i don't think it is a good idea to have a bunch of grids you move around for wtv reason.
Remember you can predict everything what will be happening in your game. It is obvious that for example there will be player grid + chest grid. Just create them and place them into the point of origin at the start. If you are having more slots like pockets and stuff. Make them in advance. At the end of the day, the hit to performance because you have like 3-4 screens done in advanced with all grids created in advance, will outweight the hit to performance if you are constantly instantiating stuff around.
If you really need to move the grid around, look into the on grid position calculation, i think something is breaking down because of how i made this grid, when you move it around.
@@GregDevStuff Awesome thanks for the quick reply!
hello love your video but i am having trouble when pressing w if i add to many objects it goes in the corner like what heppened when you pressed q, is there anyway to find out why it does not calculate when the grid is full for me?
Thanks for this tutorial. Any thoughts on using this approach vs building a similar system around IDragHandler/IDropHandler?
Not 100% sure, but i think yes it is possible to use DnD approach yeah.
This... Accent... where r u from?
nice tutorial btw, great job
man I gotta say you have done wonders with this tutorial, would it be possible to release a tutorial extending this one?
I was wondering how it would be possible to make a flexible inventory based on equipment pickups. So say I pickup a green shirt it's inventory would differ from red shirt?
ie. green shirt has 12 slots but red has 8 slots
also if something is not equipped then the inventory disappears and items ( if any were in it ) are dropped?
kinda what survival games do?
Hey Greg. I've tried this twice, and I'm copying everything you do, but the coded grid doesn't match up to the one on the screen at all. I can't get the test item to sit in the right square. The coded grid is just smaller than the one on screen. Also, you don't need to find components like that all the time. You just need to reveal the field in editor and drag and drop. Including the rect!
How could I make this scale properly with screen sizes? Do I just double the grid and sprite sizes when it goes past a certain resolution?
On my discord server there is an explanation how you can make it scalable.
Hi Greg, awesome tutorial, plenty of great code practices as well for a fairly new coder such as myself.
I have one question, i'm interested in making a non-square or rectangle shaped item.
how would i go about making a 3 slot L-shape item? Is it possible to join two rect transforms together to form this? Or am i thinking about this all wrong? Any insight would be helpful!
thanks and keep up the great content!
Yes absolutely possible. And possible to make in this type of the inventory. You should keep ONE texture/object per one Item. But on the Data layer, you know your nodes in the inventory, you should assign the actual shape of the item.
Honestly i did inventory like you mentioning, and i'll say, it is not worth the effort. IMO. But maybe your game really requires it in that case good luck.
@@GregDevStuff thanks for the quick reply, i'll try messing with that after work! 90% would just be rectangular like your tutorial, but I am messing with an idea of a charm inventory with a few more unique charm combinations.
The only other thing i need to figure out is incrementally increasing the inventory size by one slot at a time. For example if i have a 6x3 inventory and expand one slot into 7x3.
There must be a way to add another row to the array but not let the other two slots of the row be selectable yet.
Another idea would be to just have a max size, eg (10x4) and only show what is unlocked or usable. Anyways i'll play with these ideas more and come crying to you for help later :)
Thanks for the fast reply by the way mate,
love from Australia!
@@TheFlintMontana It should be possible to resize the inventory with some fenangling with code.
Бля, ребят, отстаньте вы от его акцента, как по мне британский, что очень схож с русским, является одним из понятнейших. Да и согласитесь, лучше если человек проговаривать каждое слово, как минимум в гайдах, нежеле чем произносит с "правильным" акцентом(хз кстати, что вы считаете за "правильный", наверно американский?) и при этом смазывая каждую букву😅
Спасибо Грег, очень помог гайд)
Забей, там очевидно тролль и я чото забейтился. Мой косяк. Но всеравно мне реально не понятно одно, почему вот горит только у русско говорящих на тему акцента или как тот субъекты говорил произношение.
@@GregDevStuff Скорее всего фича в школах такая, у меня был учитель, который люто дрочил за произношение. Как говорится:"Всё из детства") А гайд действительно годный👍
Hi there, ended implementing the grid in my project and found easier to have another image on the item prefab for highlight and use ipointerenter and exit methods to enable and disable, even changing color if can or can’t place the object. Just in case anyone prefers that.
That sure is easier, yet you double your object count for convinience. Which is going to affect performance on a large scale inventory.
@@GregDevStuff Good point.. mmm not an easy way eh?
Found another advantage of the second Image in the itemprefab. This way you don't need to carefuly size your objects. I went almost crazy calculating sizes in pixels to keep proportions and so on.... CRAZY!! I need to choose between performance or insanity! :)
The GridInteract script doesn't appear to work for me as the selectedItemGrid isnt assigned when I move my mouse over the grid. Also when using the debug to check when it enters and exits the grid nothing happens. I added a check to see if the inventoryController was null but it isn't so that's being assigned correctly. When using the debug in the InventoryController script to check what tile in the grid the mouse is on that also works perfectly fine. I've gone back and compared all the code I currently have and its exactly the same as shown in the video and I also made sure that the scripts are on the correct object and they are so I'm really not sure what's gone wrong and why it wont work. I do have another canvas in the scene but it is currently disabled, just in case I did try moving the canvas both above and below the other one in the hierarchy but that didn't appear to make a difference.
join Discord
ok so basically this approach needs like 3 or four major adjustments. the most important one: setting collected items as children of the grid will bug the onpoinexit event
if you add text-like elements to the item, don't forget to turn off raycast target!
Yes. Or the element will obscure the mouse input.
When live reloading i get NullReferenceException: Object reference not set to an instance of an object
InventoryController.LeftMouseButtonPress, but otherwise it works fine. Its just when it looses reference after a reload, but im not sure why or how to reinstansiate it into a working state
in object highlighting the highlighter is always above the object, not on top of the object pls help
Hi Greg Dev Stuff, i've followed along with your video exactly as your typed it yet my items can't be picked up or dragged / move at all what have i done wrong. thanks in advance
Hard to say without seeing your code, join the discord, and i can look into it on the discord.
How to remove item when we take it out of the grid? Please, brother *.*
Hi! I hope you can help me !!
I create the grid, and I debug to see the grid location for example 0,0 and when I get to the middle of the tile, it's already 0,1 or 1,0 !!!
Hey, Great tutorial! I would like to know how to add an item when the grid is hidden and it is not touching the mouse. I managed to add item but the problem is that you have to keep the mouse on the ItemGrid for the item to be added. Could there be a solution to fix it?
I think I found it. I put in the awake of GridInteract : inventoryController.SelectedItemGrid = itemGrid;
and I deleted OnPointerEnter and OnPointerExit.
What do you think about it ?
@@ZeyFightyou will have to think differentely for this. You have data storage for the items, and you want to simply add items directely to this items storage instead of using the grid we are interacting at the moment. You can join discord and we can discuss it further there.
man! you are legend! Thank you so much! What about resident evil 1998 item menu?
Its really not that different from most of the slot based inventory systems. But i'll add it into list of suggestions thank you very much for the input.
@@GregDevStuff If I pay you will you do it? just same system as resident evil 3 2001? ua-cam.com/video/1r0TSwsAHLs/v-deo.html
Hi, fantastic tut. But I have an issue with the multiple inventories. When I drag an item from one Inventory to an other the draged item takes over the OnPointer... event and it does not react on inventories that are "behind it" in the scene chierarchy. Any ideas how to solve this? (when temporarly while draging I place the item in container behind the inventories it works like a charm but... items are then covered)
SOLVED: Item Prefab had Raycast target turned off like so 19:33 but its nested elements had Raycast target still checked.
@@papatomicjusz Yep :)
@@papatomicjusz Thanks my guy!
Can you please make a tutorial on how to combine amd examine items like in resident evil village
It seems though that when trying to keep the UI scale with the screen size, it starts to mess up. Any ideas on how to fix this? would i have to change the cell size relative to the screen size?
Just want to say very awesome tutorial though, honestly didn't have any other problems. Straightforward and very understandable !!!
To solve this problem use the canvas scale factor (yourMainCanvas.scaleFactor) and multiply it by the width and height of the grid before dividing it by the mouse position relative to the corner of the grid container
By default the value of the scale factor is 1 but actually there is another script that passes the scale factor of the Canvas, It looks like this: _Grid.WorldToGridRelative(GridContainerCorner, mousePos, MainCanvas.scaleFactor);
public Vector2 WorldToGridPointRelative(Vector2 origin, Vector2 point, float ScaleFactor = 1)
{
var gridRelativePoint = new Vector3(point.x - origin.x, -(origin.y - point.y));
gridRelativePoint.x = Mathf.Floor(gridRelativePoint.x / (Width * ScaleFactor));
gridRelativePoint.y = Mathf.Floor(gridRelativePoint.y / (Height * ScaleFactor));
return gridRelativePoint;
}
I hope it will help you!
at 1:26:22 you guys should add
if(selectedItemGrid != null)
if you guys dont add this it will debug error log when alt tab or change tab
How exactly? Having a return or just another nested if? If you could provide an example i'd be happy :)
@@Nomaddev lmao i couldn't fix it
it not work
@@duriniskawaiiiiiiiiiiiiiii7593 nooooo :(
Hello everyone. Any ideas how I could implement an infinite grid inventory? Cause as of now the grid displayed is the full space. Is there a way to add like a scroll bar and have even more space below??
a little late but just make it as long as you want, put on a mask and boom
you mention elsewhere that you think theres systems here that could be done way better, whats an example of one?
great tutorial btw, this is extremely helpful
Instead of using actual position on the screen, use relative position on the screen. Extract input into seperate component.
Hello ! Any clue to handle the canvas scale? If the canvas scaler is set to something different of constant pixel size, then the positions will be offseted because of the scale. Now 32 pixels are no more 32 pixels...
Use the "Constant Pixel Size" on the Canvas Scaler, and set the Scale Factor to 1, and Reference Pixels Per Unit to 100, that way, they are always 32 pixels (or whatever the value you choose) :D!
@@tiagoalmeida2194 This is the biggest problem. Unity's tools for controlling the UI are terrible. countess ways to do it wrong, and maybe one way that will work. What about what render mode to use on the canvas? Or the camera set up.
What finally worked for me was Camera normal perspective. Canvas Screen Space - Overlay
Great tutorial! By the way, how could I make it work with non-square items like Tetris bricks( L's and Z's ) ? Thanks !!!
In the item data, you need to introduce shape, and when you are placing item use this shape somehow.
Привет, на 4:19 ты растягивал мышкой, но так же мог прямо в инспекторе ввести в поле сразу на сколько клеток строишь (64 размер клетки) 64*20 (20 клеток к примеру) инспектор сам просчитает и вставит ответ 🤔
Хороший видос, спасибо 🤗
Да кстате, я вечно забываю что мат выч можно вводить там.
@@GregDevStuff Немного комментов еще прочитал, спрашивали на русском видос, непонятные люди кнч, у тебя код перед лицом, даже если ты не понимаешь английский то код то должен разобрать 🙂
Хотя может это дети смотрят которые и то и то не понимают 😮💨
Not sure if someone found a solution for this yet, but I was able to fix (at least for me) the "index was outside the bounds of array" error that's occurring for the following line in "InventoryController": "itemToHighlight = selectedItemGrid.GetItem(positionOnGrid.x, positionOnGrid.y);".
Within the "GetTileGridPosition" method in the "ItemGrid" class, I subtracted a small float value (- 0.001f) to give basically a pixel sized buffer when going out of bounds to the right or bottom (never got the error when exiting the grid from the left or top).
My code looks like this for lines 35 and 36 in the GetTileGridPosition method within ItemGrid class:
positionOnTheGrid.x = mousePosition.x - rectTransform.position.x - 0.001f;
positionOnTheGrid.y = rectTransform.position.y - mousePosition.y - 0.001f;
It previously looked like this:
positionOnTheGrid.x = mousePosition.x - rectTransform.position.x;
positionOnTheGrid.y = rectTransform.position.y - mousePosition.y;
The errors *should* stop occurring if you're getting this error - haven't gotten the error since implementing that part to my code and there doesn't look to be unintended side-effects. So, that looks to have fixed the issue in my case.
Very good tutorial, but I can't understand why the items when the inventory is full, go beyond the border to the lower left of the screen
Hello man, I found your video so helpful But I wanted to know what changes should I do to instead of using a lot of small tiles, use a png with the tiles in the same photo. For example, I have the inventory image with a size of 3x4. Am I making myself understood?
No i'm sorry, i'm not sure i uderstand the question. Do you mean you don't want to have square tiles? Like having 120pixels / 80 pixels size "slots"?
@@GregDevStuff Sorry if i was not clear. What a meant was like, you use an inventory png already prepared and sized, with all tiles placed, and all tiles belong to that png.
Imagine every "*" is a tile.
You use a png like this;
*****
*****
*****
btw, your video it is being really helpful, as I'm starting with unity and I'm learning a lot about what you can actually do in code part.
@@unlocoahiniideamiapellido9982 Okay i get it, i think you can match the size of each tile on this png sprite and it should work fine. Should.
@@GregDevStuff Yeah, Indeed it works! Thanks, I really appreciate it. Keep it up with such a good content
Thanks for tutorial. I have an issue. When i drag an item from one grid to another, item icon “hides” under grid and i see only highlighting, but no icon of drag-able item. Help please!
The zdepth of the UI is dependent on the position of the object in the hierarchy on the scene..
Hey, did you ever find the solution? No matter what sorting layer or however I order it in the hierarchy the item always go below.
@@bebros2 SetAsFirstSibling for grid (inventory) when OnMouseHover helped. UA-cam delete my comment with code lol.
@@jarekshark1356 That worked. Thanks :)
@@jarekshark1356 Can you tell me where to insert this code? In the OnPointerEnter?
I'm sorry, I may have missed the part where you explain it but, how do you do it for the items always appears on top even with multiple grids? Also, when there is no space in the grid, it just places the item outside of it. Is there any solution I didn't see?
Its a little weak point, but at the end, ensuring items are on top through hierarchy manipulation. But today i would use more like layers systems.
@@GregDevStuff I already did the last Sibling thing, but because it dosen't changes grid when you move it around but instead it does when you click, the object stays in the inferior grid and dosen't go to the front
@@miquelnavalles6679 I would store all items on a higher layer than grids. This is the easiest solution to the problem. Sorry i improved over the time in skill. If you need more detailed explanation jump into the discord i can help you there.
@@GregDevStuff Thanks, I'll be staying in the Discord, but it appears that I already solve it. I used rectTransform to put the object to root. Thanks a lot for even responding to a video that's 2 years old. It was a masterpiece and I hope another of your videos could help me in the future.
Here's the code I used:
private void PickUpItem(Vector2Int tileGridPosition) {
selectedItem = selectedItemGrid.PickUpItem(tileGridPosition.x, tileGridPosition.y);
if(selectedItem != null){
rectTransform = selectedItem.GetComponent();
rectTransform.SetParent(rectTransform.root);
rectTransform.SetAsLastSibling();
}
}
Hey Greg, loved the tutorial it worked perfectly for me except for when I try to make the UI scale with screen size, if anyone has any suggestions I would love the help.
Hey on my discord there is a fellow who expanded upon the system. You can join and in the help channel check the pinned comments, he expands upon many features of this tutorials and i think that includes your issue.
@@GregDevStuff thanks so much
when instantiate the item it doesnt fit at the center of my grid slot
:c
how check if all tile full cant spawn??
Anyone have a fix for when you move an item from one inventory to another and it ends up behind the image of the other inventory till you place it?
Make a container for carried object. Ensure that this container is on top of everything on the canvas, parent the object you carrying to that container.
@@GregDevStuff Thank you so much you legend
Hey man, amazing tutorial!
I have only one, but probably big question. Everything works absolutely correct with "Constant pixel size" in Canvas UI scale mode. But how to make it work with "Scale with screen size"?
Заранее спасибо!
That is a common question, which probably i should adress at some point, but in that case you probably will need to calculate relative position(normalized 0..1) on the canvas, and convert it to the position on the grid.
@@GregDevStuff Ладно, попробую покопаться с этим. Еще раз спасибо!
Finally found a solution!
Firstly we need to change localScale of an item we trying to insert, so it will fit for our canvas.
Add *itemToInsert.transform.localScale = canvasTransform.localScale;* as the very first line in the InsertItem method in InventoryController;
Then we need to properly convert our mousePosition to current scale.
Just pass *canvasTransform.localScale* as a second parameter to GetTileGridPosition method as Vector2. Then divide by it while calculating tileGridPosition just like so:
*tileGridPosition.x = (int)(positionOnTheGrid.x / tileSizeWidth / screenProportion.x);*
*tileGridPosition.y = (int)(positionOnTheGrid.y / tileSizeHeight / screenProportion.y);*
And you good to go!
Hope it will help if someone is struggling with the same problem!
One note:
I'm receiving new Items from the outside, so this code works for me. If you are receiving items from InsertRandomItem() then you need to change *itemToInsert.transform.localScale = canvasTransform.localScale* to *itemToInsert.transform.localScale = **Vector2.one*
@@devilbob Hey Devil Bob! are you on Greg's discord? i tried to implement your code today and i couldn't get it to work. Id really appreciate some advice.
Hi Greg, Massive thank you for this tutorial. It helped me wrap my head around the concepts of a tetris style inventory. To help myself understand what was happening I have extended the inventory to better suit my game’s needs. If anyone is curious what you can do to extend this system here is a link ua-cam.com/video/mYZnhT6tbRc/v-deo.html. Thanks again. take care!
Great tutorial, but I have a question: I am using it in 2D, and when I change the size of my Game view, the grid moves with it (in and out of the screen). One solution I found for this is to change the canvas scaler ui scale mode from constant pixel size to scale with screen size, but then the entire inventory does not work because the items spawn smaller and placement is weird. Does anyone have a solution for this?
Yes on my discord help channel there is solution for scalable inventory.
@@GregDevStuff Ty ill join now 🙏
How much code i have to rewrite to make this work with canvas set to Scree Space - Camera? I really need to change the icons to a 3d object
The idea should be the same, only problem is controls, you can join my discord i have pinned comment explaining how to use this system with more modular control set up.
@@GregDevStuff Joined, but i cant find this lesson :(
@@alphaw1gaming85 Check the pinned comments in #help chat
@@GregDevStuff Pinned by Daniel Rey? IT WORKSSSSSS OMG.
At least the part of pick, move and place the item in the inventory. Now i've to fix the highlight that gets messy, but werever :D
I need help. I get this IndexOutRangeException error on this line .
public InventoryItem GetItem(int x, int y)
{
return inventoryItemSlot[x, y];
}
this part calls the function, if it is not there and I click close enough to the grid it throws an error
itemToHighlight = selectedItemGrid.GetItem(positionOnGrid.x, positionOnGrid.y);
my Init is this:
private void Init(int width, int height)
{
inventoryItemSlot = new InventoryItem[width, height];
Vector2 size = new Vector2(width * tileSizeWidth, height * tileSizeHeight);
rectTransform.sizeDelta = size;
}
It gets thrown for every tile space your mouse moves through that is not on an inventory grid until your mouse first enters the inventory grid. I am hitting this issue too and am not seeming to be able to find a way for it to not run that line until the first time the mouse enters an inventory grid.
Cause for some reason it seems to run itemToHighlight = selectedItemGrid.GetItem(positionOnGrid.x, positionOnGrid.y);
even while within an
if (selectedItemGrid != null)
{}
statement contains it
@@shadedergu9921 Hey did you ever figure this out?
Hey, did you ever figure this out?
@@TheRoarer sadly no
I tried everything I could but it never worked
i have no idea what happened. i did the entire tutorial. everything worked and right after i completed the "Rotate Items" section, i pressed "Q" to generate an item and test it out and it crashed unity. reloaded. tried again. crashed again. Tried to undo the code from that section and now i cant place items, nothing is highlighted, a bunch of errors. Any ideas on how to fix it? I put like 10+ hours into this and now nothing works
Discord please.
@@GregDevStuffblevin93
Join my server please.@@bryan4884
could i try this with a 2d pixel game?
Absolutely, with no changes to code whatsoever.
@@GregDevStuff Thank you so much!
To anyone else having the error "index outside of range" around 1:25:00 here's a fix that worked for me. This error happens because (at least for me) when you enable the canvas again the mouse will spawn in the middle of the screen which is outside the range of the actual inventory.
In GetTileGridPosition add:
if (tileGridPos.x < 0)
tileGridPos.x = 0;
if (tileGridPos.y < 0)
tileGridPos.y = 0;
God this was stressing me out. I hope this works. Will try it out!
Had the same error around 1:33:00 and it's because GetItem() does not check if the x/y is inside the array, you have to add a check for that
I put if(HEIGHT != WIDTH) check in the Rotate method at the end of InventoryItem.cs so only objects it make sense to rotate will.
Also, I put rectTransform.SetParent(canvasTransform); right above the rectTransform.SetAsLastSibling(); in the PlaceItem method in InventoryController.cs, as well as adding both of those lines to the PickUpItem method just below. This makes sure the items selected stay on top always and on top of other grids.
The next step is to figure out how to save this data to a save game file, like json so the inventory persists after turning off the game.
Thanks, was having the same issue.
this is just a visual, you need an actual data structure
@@Notllamalord True but don't bother with Unity start over in Godot or Unreal engine lol.
Включил видюху, и не пойму, вроде русский говорит, а вроде слова забугорные))) Эффекту ошпаренного языка нет) Или как говорят горячая картошка во рту. Ну в любом случае молодец.
Great tutorial but I can figure out something, the rest all works but when I make a item that’s 2 high it will require me to place it at the very top of the grid space for it to place where I want it instead of where it is, if anyone can help me that would be great
is it not being placed automarically?
No when I place down an object it will go downwards for how long it is
If that makes sense, like one tile down per how many tiles tall it id
@@WillowBeans123 Most likely there is something off with calculation of position. But, if you have an issue we better to discuss it over discord, will be easier to figure it out.
Ok thanks I’ll look into it
33:42