Search Unity

Question Don't get any collision by using OverlapBox

Discussion in 'Scripting' started by Deleted User, Jul 25, 2020.

  1. Deleted User

    Deleted User

    Guest

    Hey,

    i'm trying to find a way, how to find out and then prevent collisions, before I spawn a prefab to a random location. My code, so far, looks like this:

    Code (CSharp):
    1. void Start()
    2. {
    3.     for (int i = 0; i < minimalCars; i++)
    4.     {
    5.         GameObject car = generateNewCar();
    6.         BoxCollider bc = car.GetComponent<BoxCollider>();
    7.         Vector3 halfColliderSize = new Vector3(bc.size.x / 2, bc.size.y / 2, bc.size.z / 2);
    8.  
    9.         Collider[] hitColliders = Physics.OverlapBox(car.transform.position, halfColliderSize);
    10.  
    11.         int j = 0;
    12.         while (j < hitColliders.Length)
    13.         {
    14.             Debug.Log("Hit: " + hitColliders[j].name + j + hitColliders[j].transform.position);
    15.             j++;
    16.         }
    17.     }
    18. }
    In the editor I can clearly see, that two spaned prefabs are colliding with each other, but the console won't log any collision. The BoxCollider also has the correct size.

    Can someone help me?

    Greetings
     
  2. Zer0Cool

    Zer0Cool

    Joined:
    Oct 24, 2014
    Posts:
    203
    If you have scaled or rotated the transform of your car gameobject this could lead to problems. In your Raycast you check for a collider relating to a transform that is unscaled and unrotated.