Prevent GameObjects from overlapping with coll/trig. C#

Hey there,

for my game I want to create a script that prevents new buildings to be placed on top of other buildings. The problem is, that actually there is a tiny moment, when it is possible to overlap buildings (which is not intended). I guess the error is within the exit function of my collission detection script:

using UnityEngine;
using System.Collections;

// Checks whether a building collides with another in the preview-phase

public class CollisionBuildings : MonoBehaviour {

    public bool collision = true; // Is there a collision in the preview? If yes prevent the building from being build (see script: BuildingPlacement)

    void OnTriggerStay2D(Collider2D other) //When there is an collision
    {
        if (other.gameObject.tag == "Building")
        {
            other.GetComponent<CollisionBuildings>().collision = true;
        }
    }

    void OnTriggerExit2D(Collider2D other) // Once the collision ends
    {
        if (other.gameObject.tag == "Building")
        {
            other.GetComponent<CollisionBuildings>().collision = false;
        }
    }
}

The problem probably stems from the high density of buildings and therefore triggering of the OnTriggerExit2D when hovering over built buildings. Do you have a clue on how to prevent this problem?

Thanks in advance :slight_smile:

I found the problem… the error was due to another script which snapped the building into position before controlling whether any collisions occur :roll_eyes: