Here's a great class to serve as a base for you to make some really awesome systems like a Heatmap, Pathfinding, Building, etc. Stay tuned for the upcoming Heatmap video and see Grid Maps in action all over the place in Battle Royale Tycoon store.steampowered.com/app/851930/Battle_Royale_Tycoon/
So next video is Heatmap right? Then what's after that? Do you plan to show it used in a pathfinding setup or will you move onto the next topic? Thanks!
@@MalikenGD Yup the next video is covering a Heatmap. Pathfinding is definitely something I want to cover but its a pretty complex topic so that's why I haven't had the time to do it yet. Maybe using this video as a base will make it easier.
It's funny. 4 years later and copilot is auto-filling your code as I type. The impact you must have made for your work to be so widespread it gets sucked into an AI brain. Neato
16:55 if only the value in the middle of the screen changes, change your camera from "perspective" to "orthographic" in the inspector of the camera. Thank you for the tutorial, really helpful!
Thank you so much for your tutorials, Monkey. Ever since Brackeys went dark, I've sort of been lacking direction and motivation for game development, but you've given those things back to me, my dude. What a gamer. Much love.
Null Reference Exception issue: If you're having issues with Null Reference Exception when changing the value of the grid elements, try checking your test script to see if your start function is "Grid grid = new Grid(4,2,10f);" if it is, delete that first Grid and leave it as "grid = new Grid(4,2,10f);" this fixed it for me as I hadn't noticed him delete it.
@@thomasharvey2980 in the vector3 get world pos change it to: private Vector3 GetWorldPosition(int x,int z, int y) { return new Vector3(x, z, y) * cellSize; } and change the GetWorldPosition in the utilsclass line to (x, 0, y) thr u go hope it helps
If anyone is having problems implementing the EventHandler OnGridValueChanged from the end of the this video, check out 3:37 of the cool heatmap video in the series, lines 55 - 57 of the code. For this video, I implemented 22:19 lines 9 - 10, and 22:23 line 73, but I kept getting a null value for OnGridValueChanged. After implementing 3:37, lines 55 - 57 from the cool heatmap video, OnGridValueChanged got updated to a non-null value.
Quick note for what you mentioned about returning a struct around 14:30: In C#, you may also return an anonymous tuple from methods. public (int, int) GetXY(Vector3 worldPosition) or public (int x, int y) GetXY(Vector3 worldPosition) would return such a Tuple. In the first case, you can access individual values with value.Item1 and value.Item2, in the second case with value.x and value.y.
Awesome tutorial! I was just about to comment how it can be improved by making the Grid generic, but jokes on me, you already have that covered in another video. There are tons of good tutorials out there, but many fall apart once you try to go beyond the basic implementation of the tutorial. Your tutorials really show that you got a deep understanding of programming and your code is easily expandable. Keep up the good work, you are a blessing for the Unity community! Much love.
Enjoying your tutorials, thanks, very helpful. I especially enjoy that you include some testing here and there to see things working out; that helps with understanding and makes the tutorial more enjoyable. Well done and thanks!
love your vids! I appreciate all you do! personally I find the Sped up footage of you writing code to be a little frustrating as I like to follow along as you write code and I have to pause to keep up. just stating my opinion. even so, please know I do appreciate all of this ! thank you, thank you. can't wait to learn more!
I managed to turn this into a grid that works with the Isometric Z as Y tilemap that tracks elevation levels. And could expand it to keep track of tiles that extend way beyond the elevation level. Thank you for a tutorial on this awesome "tool".
@@ez4novi I will post the code on github ( github.com/dutchalphaa/Grid2DIsometric/tree/master ). I basically took all of the world position coordinates and put them through a mathmatical function that changed them into isometric coordinates and took the isometric world position coordinates into normal coordinates. There is also a method for going through every layer of the function and deciding where the top layer is EDIT: added the link: github.com/dutchalphaa/Grid2DIsometric/tree/master
@@lolownq Thanks for sharing though, but I finally made it after hours of searching about isometric grid, you are right its just about the coordinates, I manage it using X: (x - y) Y: (x + y) in world position, here's my screenshot with implementation of pathfinding prnt.sc/r8m9a5, My head got burned btw after this ;)
@@ez4novi thats grand, figuring it out on your own is way more rewarding. that being said for the people still looking for the grid implementation it can be found over on this link: github.com/dutchalphaa/Grid2DIsometric/tree/master
Hey man, I just wanted to thank you for this playlist, it definitely really helped me on my project. When I first time watches this, I did struggle in understanding several part because I'm new to c#, so I decided to watch some tutorial on c# first, then when I came back, I understand most of what are you saying, thank you for this awesome tutorial!
If you are having issues where you keep getting the camera transform position from GetMouseWorldPosition it may be because your camera is set to perspective. I was having this issue and the way I fixed it was by setting the camera to orthographic although you could also use a raycast to a plane on the grid's z axis if you want to keep the camera as perspective.
Realy useful ! thanks a lot for this grid system ! I made the Grid iterable by implementing the IEnumerable interface with custom struct for value {x, y, value: T} and it's super useful :)
Simply awesome! Working my way through all these great vids -> grid, heatmap, generics to the latest ecs pathfinding video, in hope I can integrate some of this into my 3D project... I'm already a little scared of the DOTS specific stuff.
@@skelhain hey bro im trying to add this to 3d using the x,z plane y=0 but when use the setvalue need to get the mouseworldposition always return the same point and is the position of the camera
Thanks for the tutorial man, I was looking for an aproach to fix something related to my work, and by chance this also solves a problem I've been having with a game I have wanted to make for a long time.
Thank you for building this. I went through it last week and came out with a grid map. I would like to have understood more on the basics of how to use it. I wanted to simply turn a grid tile clicked a solid color, your heat map sort of got be started but seems like more than I need. Anyway Thanks again I really enjoying learning from your videos.
I'm glad you found it helpful! For various use cases you can watch my Grid Building System to make something like Simcity unitycodemonkey.com/video.php?v=dulosHPl82A Or a pathfinding system unitycodemonkey.com/video.php?v=alU04hvz6L4 Or for a more guided step by step, a very similar grid is created from scratch in my Turn Based Strategy course unitycodemonkey.com/video.php?v=QDr_pjzedv0
Recommendation to those following along: Follow EXACTLY like how he has it! THEN, once you are done with all his grid tutorials, break things apart, play with them, and add your own spin just so you have a better feeling of the logic going on.
Hello, some questions of detail: - why specify private, while it is the default access modifier? - grid.cs: in the constructor: in the double loop, why do you prefer gridArray.GetLength (0/1) to width / height? - grid.cs: in the SetValue method, why prefer debugTextArray [x, y] .text = gridArray [_x, _y] .ToString () to debugTextArray [x, y] .text = value.ToString (); ? I am a fan of your utilities ^^.
- I prefer to keep my code as clear and consistent as possible, hiding the private would make me waste precious milliseconds thinking "if theres no access modifier then it must be private" - No specific reason, both contain the same value so use whatever you'd like - Again no specific reason, both have the same value, if you were doing that in production code you should indeed do value.ToString(); to improve performance but that's a debug line so performance is not an issue.
- explicitly specifying the accesor is industry code standard. It facilitates readability as you don't have to think which is the default accesor - Code monkey is an experienced developer and it shows. Since you are using the gridArray inside the loop it is safer to use the GetLength in the constructors. Although not really meaningful in this simple scenario, it could be that width/heaight have been modified along the way. This kind of details make the code less prone to bugs with future changes - Same as above but a slightly better way would be to specify all in the same line debugTextArray [x, y] .text = gridArray [_x, _y] .ToString () = value; Also SetValue is more of a java thing. In c# you usually use properties or, in this case, you could use an indexer
Yup that would definitely be one possible application. Currently working on making a Tilemap and then use it to make a Mining and Building System like Terraria
Hey Code Monkey, I don't know if you will see this but I was wondering if you had any comments on the differences between unity's grid component versus this grid class you created? Can you implement the two to work together? Or do the work best if they are independent? At the time of making this video did you have the grid component available to you? Does all of this functionality already exist on the grid component?
Unity's Grid class is more meant for aligning visuals whereas this class is more meant to hold logic in each grid position. Yes you could have this Grid system to store teh logic and then use Unity's Grid with their Tilemap to place visuals on top
Thanks for the tutorial. It's hard to find grid tutorials with this quality and simplicity of code. I swapped the Y axis for the Z to be flat to the ground for use in 3D projects. I will use it in a network culling and heatmap based spawn system's. I did an experiment and changed the array to a three dimensional array and it works the same way (it looks like Unity Umbra Culling). I just had to adjust error handling and debug view.
First of, love your work and contribution to the community. Just one pointer which maybe you heard before. The parts where you are doing the C# parts are done incredibly fast. Which I understand, as for you it's something your probably done 1000 tines before 😂 but these part are the more important and interesting parts for me as a new comer. A little more focus on that would make your videos better then they already are 😊
The main issue is the RU-vid algorithm, If I don't speed up the code then people drop off during those parts, or the video ends up too long and no one clicks on it. That's one of the benefits of courses, in my courses I'm not beholden to any algorithm so I can take as much time as I need
If you want the grid "top down" like in a 3d game you can rotate the TextMesh by adding this line in the main constructor >> transform.rotation = Quaternion.Euler(90, 0, 0); and for the GetWorldPosition, put the y value in the z slot like this >> return new Vector3(x, 0, y) * cellSize;
Thanks for the tip. Maybe when running the code, the mesh doesnt allign with the gizmos. In this case, its just to insert 0 in the y position when evaluate the cellSize >> CreateWorldText(gridArray[x,y].ToString(), GetPositionWorldPosition(x, y) + new Vector3(cellSize, 0, cellSize) * 0.5f);
in the vector3 get world pos change it to: private Vector3 GetWorldPosition(int x,int z, int y) { return new Vector3(x, z, y) * cellSize; } and change the GetWorldPosition in the utilsclass line to (x, 0, y) thr u go hope it helps
Can you tell me, how i can create a movepoints like a Heroes 3? (With highlight to allowed tiles) Hint where to look, please) (sorry for english if i wrote wrong anywhere)
Thanks for the tutorial. Whilst i agree with many it was not friendly to follow (clearly showing your expertise) it was at least something to work with. My question to all is any idea why my Grid is starting from the centre of the Game view but bottom left of the Scene view (UI Canvas)?
For some reason the text that is displayed is very blurry. I tried changing the pixels per unit on the 1x1 sprite in your package but that didnt seem to do much at all. Also how would you go about using this system for large maps like in Factorio or if you wanted to procedurally generate an infinite map ? Thanks
Question: why can't you just use the built in grid system Unity has, is it possible to even implement it that way rather creating a whole other grid system via script?
i'm moving on because its not that big of a deal but i was having an issue with my grids not spawning how your grids were, the two smaller ones spawned how yours did but the bigger one overlapped, so im hoping this doesnt have bigger repercussions in the future, but maybe someone else had this issue or hopefully you might know why that would happen. thanks a lot and i love your videos by the way
I cannot download the project files and utilities as I am unable to receive the verification email from your website. When I click on resend email it says error so I cannot access the files. Please share the download link
Hi code monkey I'm really new to this. To make this work for 3D terrains, you mentioned in the comments to swap XY vectors to YZ, but how how exactly do you do that? Is that done in the script or in the editor?
16:30 During this part, I get a NullReferenceException: Object not set to instance of an object using your package 🤔 This resorted to me making my own way of getting the current mouse position. Other than that, great series! I will continue to watch ✊ Edit: Figured it out, I didn't tag my camera "MainCamera" 😅
Using his numbers, my grid is huge. I know I can increase the camera size or I can decrease the cell size in the code, but how does it know what a cell size of 1 is equivalent to in the game in the first place? I changed the cell size to 1 in his code but the size if the resulting cells in the sceme don't seem to correspond to anything in the scene or in the settings that I can tell.
I guess that you already solved the problem, but in case someone else has the same issue the solution is very simple, go to the Main Camera object and increase the Size value
@@adritopoangel no not yet. My code was working but my question was, what does a cell size of "one" mean? What is it equivalent to. I know to change it, but I don't know why it ends up being the size that it ends up being when I change it to one.
@@johncotrone2767 1 here translates to 1 unit. They don't really translate to anything meaningful like a foot or meter but if you make an object at position (0, 0, 0) and another at position (1, 0, 0) they'll be one unit apart. Orthographic cameras in unity seem to use the size field as the distance from the center to the vertical edges kinda like a radius. A camera with a size of 5 will be 10 units tall and an appropriate amount wide dependant on your aspect ratio. E.g. A camera with a size of 5 and an aspect ratio of 16:9 will be 10 units tall and 17.777... units wide. With a cell size of 1 you would be able to fit about a 10x17 grid on screen. Either increase camera size or decrease cell size to get more cells on screen.
Love the video! Been wanting to work with a grid based system for a long time, finally have the time to give it a try! Quick question, I got to nearly the end of the tutorial where you click on a grid cell to change the value, but every time I click it sets the same grid square to the value. It never sets the actual grid I am clicking on, and it even changes that same grid value if I click outside the grid pattern. Have you ever seen this odd bug? [ANSWER] I found it! I need to change the "Projection" setting on the camera object itself from perspective to ortho. That was a tricky one because I tried changing the projection setting from the "#Scene" window, but I needed to change it in the gameobject. Tried going just a little bit further to see if I can identify the bug. If i use the right click to get the value, after I change the value of one tile (Which is always changing the same tile) no matter which tile I right click on after that it returns the value of that single changed tile. This is very odd. I've gone over the code you have a dozen times and can't find a single place where my code is different from yours. [Update] OK I think I found somewhat where the code is failing, but I'm not sure why it is failing. The tile that is directly in front of the camera is the tile that is being affected. So for some reason the code that is trying to find where I clicked is only finding the tile that is straight forward from the camera. Not entirely sure why its not grabbing the position of where I click. If I run: if (Input.GetMouseButtonDown(0)) { Debug.Log(UtilsClass.GetMouseWorldPosition()); } then it just returns the position of the camera, but with 0 z axis. The only thing I can think would be wrong is he UtilsClass is somehow grabbing the wrong info. After doing a ton of debugging, it all seems to be debuging properly except for grabbing the correct spot on the screen (I can debug for mouse position and it works fine)
Yeah I definitely want to but at the same time there will be quite a few changes in 2019.3 so probably going to wait until then in order to not have outdated tutorials.
Man i wish every unity tutorial was just like you fast straight to the point doesn't waste time rewriting every code , just one question I'm trying to make this for an isometric game so the cells need to look more like a parallelogram and be rotated a little bit do you have any idea how to approach it with your code
The best approach is to keep the underlying logic on a normal rectangular grid and only place the visuals on a isometric view. Or you can just do some math and convert the grid to isometric, all that matters is the conversion from world space to grid space.
Can we have the cut off part of the function for CreateWorldText at 5:37 please? I know you mentioned in some answers that the logic is already there but we would appreciate it if you could paste the rest here, so we can follow it exactly. Thanks.
I read through the user agreement looking for a clear answer, but Code Monkey's Utils can be used in commercial products as long as one doesn't break the usual rules regarding trying to resell the actual code / reverse engineer / steal credit for it, correct?
What proprietary code? My Utilities? You can write your own, there's nothing special about my own. You can download the entire source code and read it all yourself
@@CodeMonkeyUnity I was being rude, apologies for that. I skimmed the video for a some idea on what to do for a grid system, say the "CodeMonkey.Utility" directive and thought I was going to have to use your code. Didn't see that you literally show the code you are using. Super appreciate this video!
@Code Monkey I have a null reference exception error when I reference code: grid.SetValue(UtilsClass.GetMouseWorldPosition(), 56); in Testing.cs Can you please help me? I a beginner and has very little knowledge of C#. Thank you for your great tutorial videos and utilities
For the GetXY method, you should consider using the C#7.0 Tuple pattern. Microsoft consider it cleaner for multiple returns. I personally do not like multiple returns but sometimes they are unavoidable.
Yeah Tuples seem to be very interesting and would definitely be perfect in that scenario, I just haven't gotten used to using them yet. Unity is usually a couple of versions behind so I don't normally focus too much on the latest features added, although right now I believe Unity does support C# 7
Thank you for the video. I really enjoy all of your videos. If possible could you also cover saving and loading the grid with gridobjects and their state.
Thanks, great video only two questions. How do I make it 3d for the grid building system video and also for the grid building video do I have to complete both this video and the powerful generics video. Thank you
Check out the full playlist. This "series" wasn't planned ahead of time so the videos are more to teach you how the underlying logic works and not meant as a step by step course.
I have imported the utils pack but the code for creating the world text (5:34) dosn`t work. I get the error "No overload for method 'CreateWorldText' takes 0 arguments". can somebody pls help me. edit: problem solved just watch the video further!
Great video, thank you! I have a question: new Unity versions have native Grid component, are there any benefits of using custom grid implementation over using the implementation provided by Unity? Do you have plans to make a video about the native implementation?
The built-in Grid is meant for positioning objects, whereas this Grid System is primarily meant for logic. On this first video it's hard to see the difference but in future videos expanding upon this grid it becomes more clear unitycodemonkey.com/video.php?v=8jrAWtI8RXg unitycodemonkey.com/search.php?q=grid
Hey I know its just a debug but when I try to implement both the (Input.GetMouseDownButton ( )) to my Testing script, it throws this error NullReferenceException: Object reference not set to an instance of an object Testing.Update () (at Assets/Grid Scripts/Testing.cs:18) To be more specific its referencing this line of code if (Input.GetMouseButtonDown(0)) { grid.SetValue(UtilsClass.GetMouseWorldPosition(), 56); } Any ideas? You've been amazing at explaining so far. Having interactive debug would come in handy though. Thank you.
I figured it out. The solution in case anyone had a similar problem was I declared private "Grid grid;" and had never took the "Grid" away from the "Grid grid" in the update function.
Sounds like you didnt set your "grid" variable correctly. Make sure you're not creating a local variable in the Awake and instead are setting that field.
Was this video made before the Grid component was added to Unity? Because I had to replace the Grid name with GridMap and it caused a little confusion when I made the Testing script and used Grid instead of GridMap.
4:46 I would argue that this isn't the best way of iterating through the array. On each iteration, you call a method to get the length of the dimension. What you should do instead is to cache lengths before the loop and use these values. In your case you don't even need to cache them, you already have them in form of width and height parameters.
Thank you! This tutorial was very helpful. The only problem I get is that the grid appears only when I run the code, and it's also weirdly centered on horizontal. I don't know what to do and I've been stuck here
Hi codeMonkey, what if i want to get the grid on a 3D plane instead? which parameters do i need to change to take in the x and z value instead since it's Vector3?
Hello Code Monkey, long time lurker here. So my question would be: doesn't Debug.DrawLine only work in the Unity editor? What about the finished build, how do we create grids in the actual game? Do we have to use meshes (aka LineMesh) to draw the lines instead? Cheers. Also, here's an idea for a tutorial: not sure if you're familiar with how you create districts in Cities Skylines, but that looks quite fancy, it would be very interesting to know how they do that. Oh, and on a similar topic, here's something rather complex: how do you intersect two fairy complex road meshes (procedurally). So you draw a road from A to B and one from C to D and they intersect at some point, asphalt, sidewalks and all that. Or perhaps CD is just branching out of AB. How do you figure out the math for that intersection, given a road profile that is more complex than a single flat quad? Keep up the good work!
Yes DrawLine is a gizmo so it only shows in the editor, it's meant for debugging, not for players. If you want to show it to players yes you need to use something like a mesh and either draw each line or draw each quad. I made a visual for the grid in my Factory game ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-88cIVR4KI_Q.html I still haven't played Cities Skylines but I think it works like in SimCity where you just assign some grid positions to a specific type, it's really just a field inside the grid position object. Dynamically drawing intersections, yeah thats a complex topic, really depends on how you do it, would probably require a bunch of raycasts to identify the intersection and then somehow draw it.
This is really great, thank you! I wonder how much of this can be done using Unity's in-build Grid system? Like, is it possible to build off their existing system, rather than start from scratch?
From what I know Unity's grid system is only meant for positioning things, don't think you can place logic in each grid position which is the main goal of my grid system ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-8jrAWtI8RXg.html Same thing for the Tilemap, if you just want a grid with visuals then the default Unity Tilemap will work great, but if you want to add logic to each grid position then you need a different approach.
Can you explain the pure logic behind grid map for if someone wants to make this in playmaker or Bolt? & are you using list, array, hashtable or dictionary to store the gridcells and underlying grid data?
I am sorry I am try to learn how to make this for navigation on an ocean in 2d because once you add in land mass won't most of the grid be in or under the land ? Would you just make smaller clusters and lay them out manually?
Would this work in a custom Editor Window? I'm trying to make a custom map editor and everything's working great... I have two grids and can set the map grid using my tile palette grid.... except for fact that, when trying to select either grid, they both start in the top left corner of the window. So clicking in the top corner fires off that 0,0 has been clicked in both grids. However, because I use Handle to draw the lines, the grids appear to be being drawn in the correct locations. I added the Origin Vector 3 and code is exactly as is in the video except for using Handle to draw the grid lines... Been at it for hours now and eyes are getting blurry and head hurts :/
Question, my version of a grid map is creating a cell class containing a vector2 and storing them in a dictionary. So if i set my width and height to 200x200, a nested for loop would start, creating a class for each x and y and storing them in a dictionary with their keys being their coordinate. Is that method efficient? It makes accessing them easier but im not sure if its memory efficient or amthing
The other parameters are TextAnchor, TextAlignment and int sorting Order You can download the entire source code for the utilities and inspect it. Essentially that function creates a game object and adds the text mesh component to display the text
Is this method creating grid coordinates or simply reading off world values? Could I set up multiple grids or grids not aligned with each other? (Without doing a stupid amount of math.)
Not sure what you mean, the Grid has an origin and a cellSize, those parameters are what relates to real world units. Yes you can set up multiple grids, that's how I made my house building system unitycodemonkey.com/video.php?v=gkCBCCKeais
If you have it you can attach it to a game object as a component and you have access to the standard functions like Start() and Update() If you don't add it then you have a standard C# class. If you don't need to add as a component or you don't need the functions then there's no need to make it a MonoBehaviour
Hi. Great video. I'm new to Unity and have been trying to understand why would I want to create my own Grid class instead of using the Grid component already provided by the engine? Does yours have features that the other doesn't; or maybe solve certain problems in better ways?
Unity's grid is meant for positioning objects, whereas this grid is meant for logic. So if all you want is to position objects then sure use the built-in Grid But if you want to store logic in each grid position, like a Unit reference or some Pathfinding data, then you need a different structure. You can watch the later videos on this playlist to see more advance use cases of this grid system like this one unitycodemonkey.com/video.php?v=Cdcn6uK9gPo
my testing script: using System.Collections; using System.Collections.Generic; using UnityEngine; using CodeMonkey.Utils; public class testing : MonoBehaviour { private Grid grid; public int xx; public int yy; //i made xx and this to have some control in the inspector. // Start is called before the first frame update void Start() { grid = new Grid(xx, yy, 10f); } private void Update() { if (Input.GetMouseButtonDown(0)) { grid.SetValue(UtilsClass.GetMouseWorldPosition(), 1); } } }
my grid script: using System.Collections; using System.Collections.Generic; using UnityEngine; using CodeMonkey.Utils; public class Grid { private int width; private int heith; private float cellsize = 10f; private int[,] gridaray; private TextMesh[,] debugtextaray; public Grid(int width, int heith, float cellsize) { this.width = width; this.heith = heith; gridaray = new int[width, heith]; debugtextaray = new TextMesh[width, heith]; Debug.Log(width + " " + heith); for(int x=0; x= 0 && y >= 0 && x < width && y < heith) { gridaray[x, y] = value; debugtextaray[x, y].text = gridaray[x, y].ToString(); } } public void SetValue(Vector3 worldPosition, int value) { int x, y; GetXY(worldPosition, out x, out y); SetValue(x, y, value); } }
Is there a way to set up a grid to appear and be edited within the editor? So I can set up a grid to use for various gameplay reasons, but not have it shown to the player.
How could I go about making the cells have a width and height rather than just a single number? Like cellsize.width, cellsize.height for example, so the cells could be rectangle rather than square. Great helpful video btw.
The "shape" of the grid is all defined in the functions that convert a world position into a grid position. You need to change that calculation to take a width and height into account instead of doing a simple Round/Floor