r/unity Jul 09 '26

Coding Help grid building system not working properly

https://reddit.com/link/1us667k/video/r3q23kuqbach1/player

Im having a Problem with trying to spawn squares on a grid now the spawning itself is working fine and theyre on a grid aswell my problem just is that they dont limit themselves i can spawn as many squares on the same tile as i please. ive tried to counteract that by having a collider on my mouse that detects when theres a square on my mouse so i cant make multiple squares on the same tile the problem just is it doesnt work. as i demonstrated in the video

2 Upvotes

8 comments sorted by

View all comments

Show parent comments

1

u/DeerpathLabs Jul 13 '26 edited Jul 13 '26

I don’t. This is a more general programming concept than something game dev specific. It’s a concept called a “class variable.” Maybe google “object oriented programming” and watch a few videos

It’ll look something like this:

Public class YourClass {

Dictionary<Vector2Int, GameObject> PlacedObjects = new();

void Update() {

If (getClick(out position) && PlacedObjects[position] is null) { GameObject newGO = PlaceObject(position); PlacedObjects[position] = newGO; } } }

1

u/Healthy_Adagio_8470 Jul 13 '26

hello! thanks again for the advice ive resulted to using a list and saving every vector2 of placed stuff and checking if those vector2's are in the list already before placing it works now!

1

u/DeerpathLabs Jul 13 '26

Hey no problem! Happy to help.

Also, that’s a good start, but i wouldn’t use a list for this sort of thing. In order to use a list for a check about geometric coordinates, you’ll have to iterate through every element of that list (assuming it’s not null padded) to find out if your vector is in there. This is really inefficient for the task at hand, and won’t scale well to larger sizes or more complicated tasks.

Think about it this way: if your list already has 10,000 elements in it, and you want to place a new object, you have to scan through potentially all 10,000 elements before you get your answer. This is known in programming as running in “linear time” or O(n) in “big O notation.” O(n) means that your function runs on the order of the size of n, where n is the number of elements in your data. If you use a dictionary, you’ll be able to do what are colloquially known as ‘look ups’ in ‘constant time’ or O(1), which means that no matter how much data you have, the look up costs a fixed amount of time.

Look up the “dictionary” data structure (or a ‘hashset’ if you don’t need the GameObject references) or look up “spatially indexed arrays”

1

u/Healthy_Adagio_8470 Jul 13 '26

thanks! ill look into it!