Search Unity

How do I call collision while still in Editor mode?

Discussion in 'Scripting' started by Ragee, Sep 17, 2017.

  1. Ragee

    Ragee

    Joined:
    Nov 24, 2012
    Posts:
    15
    I might be approaching this wrong but what I am trying to do is to delete game objects based on a mold while in editor mode.

    I have created a level mold in Blender and imported into Unity.

    In unity I have cubes instantiated 30x30 and with the level mold I want to remove the cubes that are touching the walls of the mold to create the same shape in unity but built up by boxes.

    What I cannot figure out now is how to call collision while editor or is there another way I can approach this?

    I have tried this:
    [ExecuteInEditMode]
    public class DeleteWalls : MonoBehaviour {

    void OnCollisionEnter(Collision col)
    {
    if (col.gameObject.tag == "Wall")
    {
    Destroy(col.gameObject);
    }
    }
    }
     
  2. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,089
    You could try 'OnCollisionStay' which is called all the time, not sure if it works in edit mode though. Alternatively you could add an Update function and check manually for a collision using Physics.OverlapSphere / Physics.CheckSphere etc...
     
  3. Ragee

    Ragee

    Joined:
    Nov 24, 2012
    Posts:
    15
    Thank you for you reply.

    Struggled to get my head around Physics.OverlapBox at first but it now works for me

    In case it can help someone else this is the code:

    Code (CSharp):
    1. static void RemoveBlocks()
    2.     {
    3.         GameObject[] walls = GameObject.FindGameObjectsWithTag("Wall");
    4.  
    5.         Vector3 halfSize = new Vector3(1f, 2f, 1f);
    6.  
    7.         int i = 0;
    8.         while (i < walls.Length)
    9.         {
    10.             Collider[] colliders = Physics.OverlapBox(walls[i].transform.position, halfSize, Quaternion.identity);
    11.             int c = 0;
    12.             bool collided = false;
    13.  
    14.             while(c < colliders.Length)
    15.             {
    16.                 if (colliders[c].gameObject.tag == "LevelMold")
    17.                 {
    18.                     collided = true;
    19.                     break;
    20.                 }
    21.                 else
    22.                 {
    23.                     collided = false;
    24.                 }
    25.  
    26.                 c++;
    27.             }
    28.  
    29.             if(collided == true)
    30.               DestroyImmediate(walls[i].gameObject);
    31.  
    32.             i++;
    33.         }
    34.     }
     
    Last edited: Sep 24, 2017
    Tonymotion and tonemcbride like this.