Removing Objects - Grid Placement System P7
Вставка
- Опубліковано 29 чер 2024
- In this Unity tutorial we will learn how we can remove objets from our grid placement system (data and the GameObject representation).
House building system in unity project template:
courses.sunnyvalleystudio.com...
Starter Project:
/ 80441380
Scripts on github:
github.com/SunnyValleyStudio/...
Assets used:
kenney.nl/
𝗛𝗮𝘃𝗲 𝗮𝗻𝘆 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀? 𝗝𝗼𝗶𝗻 𝘁𝗵𝗲 𝗱𝗶𝘀𝗰𝗼𝗿𝗱!
/ discord
𝗣𝗟𝗘𝗔𝗦𝗘 support the channel:
/ sunnyvalleystudio
00:00 Adding Removing State
02:23 Preview for removing state
05:34 IBuildingState implementation
08:20 Removing Object From Grid Logic
10:58 Removing Object GameObject Representation
13:26 Checking Remove Validity
15:06 Using Removing State
17:10 Testing
17:55 Adding Sound Effects
#unity3d #gamedevelopment #indiegamedev #sunnyvalleystudio
Hey! Since the video was pretty long I did not add the HIGHLIGH red logic to the object. I will try to cover how to do it (or a better way) in a separate video. Sorry about that! 😅
u are amaizing!
Thank you so much for this tutorial! I started learning last month and this has given me an amazing base to build upon. Your tutorials have been some of the easiest to follow. Thanks again!
Great to hear! 👍
Just finished following the tutorial. Great videos, thank you so much!
Glad it was helpful! 👍
Besides great sims-like system, I want to say thanks for the best explanation of state machine pattern. Patterns in general is a big problem for me, so ur tutorial series really helped me
Glad to hear it 🙂
Great tutorial serie, very enjoyable and great explanation
Many thanks! 🙂
the course going awesome, pls continue 😊😊
Thanks!
Amazing tutorial. Thank you!
Thanks for watching 🙂
The training course was excellent, I enjoyed it
Great to hear! 🙂
thank you, this is still work perfectly...
Great to hear!
Incredible videos bro! It was super useful, I hope that u can grow in yt to have more tutorials like this! Thanks you!
Thanks for the comment!
hi man, i just have to say that i am very thankful for this series, you improved my skills as a dev a lot, I am trying to update the code so i can move already placed objects in the grid, if u have time, i would appreciate you helping me, thanks
Glad to hear it! Feel free to join discord and ask questions there!
Hey, thanks for this series! Could you show how to add a turning and flipping of these objects? Thanks you in advance!
Good tutorial I got lost around video #4 once your .cs quantity went from 3 to 9. So I asked GPT to implement this system and it did in a single script, not counting scriptable object, 280 lines of code which even included rotation. But the code is heavily commented so maybe 180 of actual code, it was easier for me to follow and read comments.
Good to hear!
Can you send me the script ?
@@Dalihkiri you're not going to be able to use it, its tied to the scene; manager.cs, scene's layers, and tags. If you're trying to do rotations or just to alter anything in this tutoria's series video 1-7 the best advice I can give you is OnDrawGizmos() to visualize how the dictionary is storing grid's cell data, add a debug.log so you can see which grid cell data you're clicking on, and finally label your entire grid so you understand where every worldtocell grid position is. And as far as rotations, you will need an offset function for square objects, like 2x2 or 3x3 or 4x4 and you will need an additional transpose function when rotating no square shapes such as 10x1 or 6x5 or 2x1 for the first and third rotation. But the AI will give you all of this very fast and easily you just need to be able to troubleshoot or understand what is being changed or what it needs to be changed to and for this OnDrawGizmos is a must, make sure to have your Gizmos enabled in the top right corner of scene view, good luck!
@@Dalihkiri I posted a reply but youtube is not showing it.
You got a subscriber!
Thanks so much for your support! 👍
Congratulations for the tutorial, it is helping me a lot in a class project, one question in the future, there will be a video on how to rotate the objects before placing them, it would be useful to place, for example, different chairs around a table, it would be great since it would give more construction realism
No. I cover it in my House Building template though courses.sunnyvalleystudio.com/p/house-building-system-in-unity
Rotating a 1x1 is easy - just make the chair a child of a parent object with a pivot point in the center of the cell. Next whenever you press the rotate button rotate this parent object by ex 90 degrees.
Placement of a bigger objects that are rotated requires a more elaborate changes to the placement validity check ( I mention creating 4 for loops to check placement depending on the rotation).
very good tutorial. THX. For those who are - like me - annoyed that the placedGameObject list is getting longer an longer: I add up some lines of Code in PlacedObjects, so it checks wheter there is a free slot from previosly deleted Objects and recycles them:
public int PlaceObject(GameObject prefab, Vector3 position)
{
int index = 0;
GameObject newObject = Instantiate(prefab);
newObject.transform.position = position;
for(index = 0; index < placedGameObjects.Count; index++)
{
if (placedGameObjects[index] == null)
{
placedGameObjects[index] = newObject;
break;
}
}
if(index == placedGameObjects.Count)
placedGameObjects.Add(newObject);
return index;
}
It might be cleaner to delete the List-Entries, but this would result IMHO in an immense Code refactoring, because of the adressing by indices. so this is quick'n'dirty :)
Thanks for sharing! Yeah I have implemented similar logic in my House Building Project template 🙂
Hello, your a building an amazing tutorial here!
1 question, will come in the future a video with "rooms" that must contain x objects to be a valid "room", that would be awesome, that is a mechanic more of hospital games than the sims, but systems are very similar
Hey! Thanks for the feedback! I will see what I can do 🙂
Hey this is an awesome series. Do you know how to save the objects so the player can reopen the game and their placed objects will still be there?
We would need to convert the Dictionary that we have inside the GridData class into some sort of a Struct containing an int ID and a List representing the positions occupied by this object. We would save it to ex JSON flle. I will link a video series later. When we have that upon loading the game we would need an extra method that would add the loaded positions and ID to the GameData. To use ObjectPlacer to place the object we would have to calculate the position with lowest X and Z coordinates as the origin position.
Here is a longer series where I explain the save system on an example project studio.ua-cam.com/users/videoEZ-AaPgaL28/edit
Hello, great tutorial. Although I do not understand why we need the ObjectPlacer class with placedGameObjects List. Cannot we do all the checks if object already exists via the GridData. We store the information there anyway. And it is indexed by the Vector3Int.
Definitely we can! Object placer is my way of separating the visual side from rendering. This way we can more easily save and load data to GridData and place objects using the ObjectPlacer and the already existing logic. That was the idea.
I know that I have coupled some feedback sfx / vfx with current placement states so we would need to refactor this code. But that is just because when designing this code I didn't go that far so it would be next refactoring point for me 🙂
I am following your excellent tutorials. Could you advance the tutorial with the option to rotate objects and the placement of walls?
Thank you so much!!!!
Thanks for the feedback! I will think about it 👍
Hey, it was a great tutorial, and I have finally managed to finish it ... I still have a question... I don't get the difference between the floor data and furniture data, mainly because we never set the floor tile in the scriptable object as a floor ... or did I miss something? can you please explain the purpose for it , and when /where in the script did we set up our place-able objects to a particular floor/ furniture data .. I don't seem to be able to figure it out ... thanks
After waiting for a reply I decided to load all scripts into chat GPT and ask the same question! this was a reply :
In the PlacementState script, there's a line of code that determines which type of object (floor or furniture) the selected object is based on its ID:This line of code uses a ternary operation. It checks if the ID of the object (retrieved from database.objectData[selectedObjectIndex].ID) is 0. If it is, selectedData is set to floorData. If it's not 0, selectedData is set to furnitureData.
The logic is simple: If the ID is 0, it's treated as a floor object. Otherwise, it's treated as furniture.
I am literally blown away, and now I actually remember you talking about it and even saying if there were more floor objects we need different logic ... but for some reason, I completely forgot about it
Good to hear! The fact that you didn't get that when i was talking means that I should put more work into those vids.
I should really figure out how to make chatgpt record those tutorials 🙂
Thanks for the tutorials, they have been so useful and well explained! Any chance you will expand and add a section for rotating objects?
Also, is there an easy way to have objects placed at the centre of the cursor/grid point? I tried modifying the scripts which messed up the previews and remove state, I also tried altering the prefabs but it seems awkward and didn't work smoothly :/
Hey! In general you could apply some offset to the preview object and to the grid check (so add size / 2) to place the object from its center tile. It should not be difficult but you might have to add in a few places to make it work.
I cover the rotation in my House Building Template project at courses.sunnyvalleystudio.com/p/house-building-system-in-unity
@@SunnyValleyStudio I was not clear from your website, is this a full course with videos or is it just the project files?
Hi :) I have a question. Were you able to change the offset so that objects were at the center of the cursor?
Hello, great tutorials, loved all of then and they were very informative. I have something to ask you. Could you please make a video showing your visual studio settings? In my VS the quick actions don't work like yours whatsoever. I don't get quick actions for constructors or anything which I feel anoyed because I see that it gives you better productivity. Thank you.
I am using Visual Studio 2022 as IDE. It by default comes with some cool refactoring options that you can access by "Alt+Enter" or "Ctrl+."
VS Code is a more limited in terms of refactoring. I think they have implemented the AI through plugins but until you earn > $200K I would go for visual studio 2022 (and if you are you probably can pay the license).
@@SunnyValleyStudio Hello, thanks for the answer. I'm using Visual Studio 2022 too, but still the options you have in the quick actions are no were close to mine. There is no build constructor quick actions, nothing. Don't know if you're using the default versions, if you have any pluggins/extensions or what not.
Great tutorial series! I have a question though. For my game, there are resource nodes and others environment pieces around my map (trees, bushes, etc). How would I make it so the player can't place objects on those locations where they are touching those environement pieces? Thanks for any help!
Hey! You would add another grid data that represents "obstacles" or "vegetation" (not sure how granular you want to go). Next in every state (or in base state) you could have a check "Is there an obstacle at this position in my ObstaclesGridData" when you call "CanIPlaceObject()" method (i think we had a mother called like this).
@@SunnyValleyStudio Thank you for this, the only problem for me is how I should add these obstacles to the ObstaclesGridData, like if I have shrubs and things already on the map, how do i make sure the player cant place a building on them.
Thank you
Hello, I’d like to start off by thanking you for this series, it has been very helpfull untill now. I was wondering, how exactly would I go about implementing rotation to the objects we sre placing? I’ve been trying for some time to make a rotation state, however, it is breaking the system. I would appreciate it if you could give me some directions, as I have been struggling with this for the last couple of days. Please help me with this!
For 1x1 objects you can add a RotateionParent object placed in the middle (so with offset 0.5 on x and z) and place the model inside it. By rotating the Rotation parent you can rotate the model and it doesn't affect the system of ours. For an asymetrical object ex 2x1 it is a bit more difficult. It changes how we need to perform placement validity check - we need 4 different for loops and select one based on rotation.
I implement it in my template if you want to see my exact implementation courses.sunnyvalleystudio.com/p/house-building-system-in-unity
@@SunnyValleyStudio So if i buy the template, would I be able to easily implement the rotation? I mean, would it be easy to implement it with the system that was made with your tutorials, or would I need to change more stuff around?
Hi, thank you so much for the tutorial series but unfortunately I didn't really understand states lesson and now I'm trying to edit the code to remove objects on right click. Can you give me a short explaination on how to do that or at least paste a code snippet for it? Anyways, amazing content
A big thank you for the excellent tutorial! I've got a question: How can I design a grid with a unique shape? I'm aiming for something more complex than a square, envisioning a formation akin to a house with special floor shape. It doesn't have to stick to the confines of a square or rectangle. I appreciate your assistance immensely. Thanks!
I would check out this library www.boristhebrave.com/docs/sylves/1/
Remember that you can have multiple prefabs or generate the mesh to adjust its shape while still using Squares. This way it is much easier to do calculations on the structure and you still can create visuals that makes it look like it is not grid based.
@@SunnyValleyStudio Thanks a lot for that
Hey! Besides Rotation, the Objects can be placed on the edge of the grid in some places. How do I fix this? I also even straight up copied your code just incase I Was somehow doing it wrong and it still occurs.
Check out my project template to get all the features courses.sunnyvalleystudio.com/p/house-building-system-in-unity
To limit placement you would just need a script defining the size of the board and check against it "IsPlacementOutsideBOunds(Vector3Int pos)"
The rotations is more tricky as it requires changes to the Placement Validity check - or rather you have to correctly calculate the positions that will be occupied based on the rotation. It's not something I can quickly explain - that is why I have the paid project where you can check it all out 🙂
Thanks for the tutorial! How can i make new objects to place? The position is never correct if i create my own.
Please check how the prefabs are structured. They have a parent object and a child object. I think we also had a middle object that was a pivot point. The idea here is that we have to place objects starting from the bottom-left corner. That is why we need to make sure that the prefab takes say 2x2 or 3x3 tiles and the pivot point is the center of the bottom-left tile. I hope it makes sense?
I am sure that if you take a look at the prefabs it will! If not feel free to join the discord channel (link in the description) since there I can share some images to better explain this concept 👍
@@SunnyValleyStudio Thanks!
Can I know where I can find the audio asset you used??
All of them are cc0. I think most of them are from freesound.org/ (and postprocessing them in Audacity) and some might be from one of the packs from github.com/sparklinlabs/superpowers-asset-packs
Hi, I liked your videos very much, this system is perfect for my Minecraft-like game, but I wanted to know if there is a way to destroy objects or generate objects by script, cause this system only let users to create and remove but I want to make walls that can be braked and structures that generates by themselves but the data makes the objects stay there if the wall itself is destroyed and if a wall is already there you can still place an object.
Are you planning to make a video about it or at least give me an idea of a script that can generate and destroy walls without user's intervention? thanks in advance.
The solution is to add a new method that before we start the game enteres the correct state - ex placement state, select the index form the database and places the object without playing the feedback sound. I have already tried implementing that in another project and the only big refactoring here is to stop playing the feedback sound by passing an extra parameter and to stop showing the preview (which is a bit more complex) but again usually can be handled by adding a separate bool parameter.
How do I move the object after selecting it, then pressing Q to move? Then it should move like out preview object then click to place.
I mean I am able to do it but it is messing up this whole workflow of state pattern and im having to do it via another update (which isnt working)
pls let me know how we can achieve this?
In my first attempt I have created it as a separate logic from the states but now that I think about it we could just delete the selected object and reenter the placement mode (reuse the existing states). That is how I would approach creating this logic.
How i can get the borders cells of my grid, if i want to start by walls on all limit of my Grid?
In my paid version I have a separate script called "GridSize" that defines the size of the gird. We could make it control the shader but the main usage of it is to allow us to check if we aren't placing objects outside the bounds. You could also use it to get the tiles around the bounds of your map.
You are a great man. Can we get a shop system?. Means after buying objects we can place it.
If you make a tutorial it will be very helpful for us.
Thanks for the feedback! I will put it on my list of ideas for tutorials! 🙂
@@SunnyValleyStudio thank you boss❤️
First of all, thanks for this series. I want to rotate objects when I right click, but it always rotates relative to Pivot. I can't rotate relative to the center.
Very often the 3D models are created with different pivot points. If you can produce your own 3D model you can adjust them to fit your design. Otherwise it is easier to create prefabs from the models so that the parent GameObject is in the pivot and it rotates whitl the model is placed in such way that the parent GameObject is its pivot in the center.
I hope it makes sense
Someone knows hot to make the object Highlighted when hover the mouse to remove??
Hello! I am currently making a builder game! However I am still quite confused on the placement validity and grid data logic. I am trying to add obstacles to the game where they are already on the map and also cannot be removed. I have also made it so that it would cost currency to place down objects down. I added another field "Cost" that would decide the cost of the different ObjectDatas. It works for placing however when removing, I can't access the cost as it does not use the ObjectDatabase. I hope you can help me out with this!
Hey!
I would just check how much money do we have and block the objects that you have in the Ui that are too expensive from bein placed. If you are already placing an object and you run out of money I would just prevent placement with some condition.
For the removal I would do exactly the same. The problem of not being able to access the Money data means that you would have to figure our where to put this code. That is why we have PlacementSystem.cs script. Here you can add GENERAL logic that applies to all the states such as money issues. For structure placement you could just as "What is the price for id X ?" next in the "PlaceStructure() before doing anything else I would ask "do i have enough money?"
I hope this helps
@@SunnyValleyStudio Thank you for helping! However I am still unclear on how to make obstacles that are already on a grid position but cannot be removed.
Any idea on how to rotate furnitures before placing them?
For a 1x1 object you can just add a RotateParent giving it position 0.5 on x and z and placing it the object. You can add the code to rotate it and apply the rotation when you instantiate the object. For a bigger object 2x1 it is more tricky as you need to modify the placement validation logic. I have added the rotation to the Project Template if you want to explore how I have implemented it courses.sunnyvalleystudio.com/p/house-building-system-in-unity
Would be nice to know how to rotate objects on the grid
To rotate objects all you need is to include the rotation angle in the grid checks. For example if you have object of size (X = 2, Y=1) and rotate it by 90 degrees to the right it becomes (X = -1, Y = 2). You can use that to calculate the offset from the placement point (the bottom-left corner for placement at 0 degrees). If you have that all you do is have for example 4 for loops (because we would have negative values) and select the one based on the negative/ positive values of the size (or now offset) and check if fields are free. Next you just use the rotation in degrees to place the prefab correctly (you would now have to save the rotation i our data).
It is a bit tricky to implement that is why I am including it in my project template courses.sunnyvalleystudio.com/p/house-building-system-in-unity
how do I remove the grid if I use a virtual camera(CinemaMachine) ????
If you don't want to see the grid when using a specific camera just go to the camera settings in the inspector and disable the rendering of the Layer that the grid is on.
Hi pls help me how can ı rotate GameObject
The best way to do it (how I do it in my paid template project) is to assume that you are always placing the object where your courser is and next use the object size and rotate it (so if it is (x:2,y:1) by default and you rotate it by 90 degrees to the right it will be (x:1,y:-2). Now you need to use this as an offset and calculate the correct positions for placement and rotate the preview object. Sorry it isn't that straightforward.
Can you please add feature to rotate the objects before placing it !
thank you
Hey! Rotation it is part of my paid project template that you can grab here courses.sunnyvalleystudio.com/p/house-building-system-in-unity
This is because rotation is a bit tricky to implement and I cover multiple ways that objects can be rotated. I explain it all in one of the videos of the project 🙂
can you do walls next?
Hey! You can check how to implement the wall placement in my House Building project template courses.sunnyvalleystudio.com/p/house-building-system-in-unity . I have added explanatory videos of how the wall placement works.
unfortunately there's no shader graph in your project grid is missing there :(
I'm pretty sure it is there. I have feedback from at least 50 people and no one had a problem with shader graph.
@@SunnyValleyStudio i can assure there's no folder called samples to get grid shader graph. Inside there's only one shader graph which is broken because of missing stuff. I tried to download both of them UnityPackage and zip as well but they are the same. I tried to open your scene and there's no shader as well. I'm currently can't follow your tutorial in any way because missing of this shader but i really want.
I have the same issue after I imported the package there's no shader... Did you figure it out?
@@nikoart1561 Nope... I did my own Shader but i have an issue position i think because of shader so I still don't. I will try to look others tutorials since this one i can't follow because of this.
Same here there's no shader inside the package. How did you do the grid?
At least dislike button work.
how about rotation?
Rotation is a bit tricky to implement as you need to recalculate all the tiles after rotation.
I have implemented it to the paid version of the project with the undo functionality and other additional features if you want to check it out 👍
@@SunnyValleyStudio You could also make duplicates of the model and then just change the model when you press R (btw i mean rotation when you are placing)
No object rotation seems like a bizarre choice.
You are right. I was trying to use it to motivate people to grab my paid project template since that is the only way i can get people to support my work. But it was pretty dumb. Well you live and you learn 😅
unfortunately your tutorial doesn't work on mobile devices and you are still using the old control system for some reason ;(
Thanks for the feedback. We are using "mousePosition" so it will not work on a mobile device (unless you connect a mouse to it).
Feel free to read how to migrate from old to new input system here docs.unity3d.com/Packages/com.unity.inputsystem@0.9/manual/Migration.html
What do you mean "for some reason ;(" ? What is wrong with old input system?
I completed this tutorial just in time for Unity to kill their game engine....
Sorry to hear that! I still hope it was useful for learning how to set up a grid system 🙂
@@SunnyValleyStudio Yes, I'm sure I'll be able to apply this in some way to another engine. I also appreciated your mention of the design patterns, not too many tutorials even go into that.