Search code examples
unity-game-engineeditorcollisionbounds

Detect collision inside editor


I am creating an editor extension to easily create 2D and 3D levels. I can move a generator box using arrow keys and place a prefab assigned on the num keys. The problem is I want to check that, if the prefab is already at that position, then it will either not allow another prefab to spawn there or delete the new prefab.

Any help would be appreciated.


Solution

  • I can think about two possible solutions, here. The first one is by using Physics.OverlapSphere. I report the example from the Documentation:

    using UnityEngine;
    using System.Collections;
    
    public class ExampleClass : MonoBehaviour {
        void ExplosionDamage(Vector3 center, float radius) {
            Collider[] hitColliders = Physics.OverlapSphere(center, radius);
            int i = 0;
            while (i < hitColliders.Length) {
                hitColliders[i].SendMessage("AddDamage");
                i++;
            }
        }
    }
    

    Basically, with this method, you check for the number of colliders that occupy the given area (the area itself is determined by a centre and a radius).

    Another, more "basic" solution would be keeping a data structure (like a Map) containing the spawns' informations (like the coordinates of the already instantiated prefabs): this way, you can check directly from the Map if a prefab has been already instantiated here.

    Hope this helps!