Hello,
I have a grid of 100 x 100 empty gameObjects that I spawn on my scene, each empty has a collider attached to it, with a size of 1 x 1. So when the grid is laid out - they all fit snug against one another.
The grid is used to show where the user can, and can’t deploy a building (in the future, the grid will have a white texture to show the user can deploy here, and a red to show this cell is unsuitable for deploying).
I’m currently using a box collider to on my building, that when collides with my grid colliders - sends a ‘IsHighlighted’ message. Which returns info about the cell - if its a good cell, or a bad one.
My question is -
I’m I better using a Box Collider, as I am doing - and using OnTriggerEnter to get all the cells under the building - which could be in the 100s count.
Or
As all my buildings are square, or rectangle - I could use a raycast on each of the corners of the building - that fires down to retrieve the cell. So my raycast will pull 4 cells in total (each corner of the building), and then use a for loop to find the cells within these four points, based on their Vector3.
Which way is better? In terms for performance and optimisation?
For you guys visiting this page in the future, RayCasting is WAY more performant than unity’s physics system, but these guys are right in saying that this user needs to look for a better, more performant way to do things. Physics really should be used as a last resort (unless they are used as actual physics, but even then it might be better to modify the original system than use what they have).
Having hundreds of collides is not the way to go for solving a problem like that. I recommend you hold a matrix in memory of the size you need (ex: placement[100][100]). This matrix will hold 1 if that position can have building placed on and 0 otherwise (or vice versa).
Now when you want to place a building you get it’s position and check that with the placement matrix. So lets say you want to place a building at x 45, y 56.
If placement[45][56] == 1, place building
else, don’t place building
having a big matrix like that can be very daunting to fill manually, so I recommend you make or use some kind of editor.
Using the technique above should yield greater performance that your original idea.
Why not put a collider only on placed buildings? Thus you can check for collision with the building you try to place. Then you just have to check for collision between placed buildings and the building you try to place. If it collides, you display it as “not placeable here” and in the other case, you build it. Could it solves your problem?