OnTriggerEnter not being called soon enough (or something?)

I am making an RTS game where you can place buildings by clicking.

When you are placing buildings the outline of the buildings appears on the floor, and if this outline is colliding with anything, you wont be able to place the building. This works if you’re acting normally, however, if you already have a building placed and you’re trying to place a building by continually clicking and spinning the mouse around like a maniac then it is very common for buildings to be placed intersecting each other.

I tested this by being able to place infinite buildings and filling the area up with buildings, obviously not a scenario that should happen in the game, but the bug could still happen if you’re moving your mouse quickly while placing a single building, I guess.

I’ve tried using all 3 of these at once:

function OnTriggerExit() {
	canPlace = true;
}

function OnTriggerStay() {
	canPlace = false;
}

function OnTriggerEnter() {
	canPlace = false;
}

however the issue still occurs.

My guess is that somehow the above functions are called after the update function, in which I have this code:

if (Input.GetMouseButtonDown(0) && canPlace)
	Instantiate(placeObjects[placeType], Vector3(mousePos.x, 1, mousePos.z), Quaternion.identity);

But I really have no idea why, sorry this question is so open ended, but what is going on here, and how do I fix it?

unity´s colliders can´t handle to fast things, i think that you should use raycast instead, it´s more accurate

I would use a raycast. Cast the ray from your main camera towards the mouse whenever you click to place something and check if it is colliding with anything. Based on the size of the building you are trying to place, you could cast like 5 or so raycasts, one for each corner of the square (assuming your buildings are squares), and one from the middle. From the raycast hit you can get the collider and check the tag or name of whatever you hit, and quickly determine if you can build there or not.

I would still keep your trigger checks in place, to use that for the GUI. (Outline of building turns red if you can’t build there, and green if you can).

If you haven’t used raycasts before just google them, they’re easy to use, and you’ll quickly find out how useful they actually are :slight_smile:

Deleted my old answer due to me typing it hastily and it sucking in general. This should be more correct:

private var collisions : int = 0;

function OnTriggerEnter(c : Collider) {
  collisions++;  
  Debug.Log("Currently colliding with " + collisions + " objects");
}

function OnTriggerExit(c : Collider) {
  collisions--;
  Debug.Log("Currently colliding with " + collisions + " objects");
}

public function CanPlace() : bool {
  return collisions == 0;
}