Search Unity

Bug? Physics2D.OverlapAreaNonAlloc's returned int != results.Length

Discussion in '2D' started by Deleted User, May 12, 2015.

  1. Deleted User

    Deleted User

    Guest

    I'm using Physics2D.OverlapAreaNonAlloc() to check if an object is near another object. The int return value is 0, but the results.Length (3rd parameter in the documentation) is actually correct and equals 2.

    From the documentation, I would think they should be the same. How can they be different?

    Documentation: http://docs.unity3d.com/ScriptReference/Physics2D.OverlapAreaNonAlloc.html
     
  2. keely

    keely

    Joined:
    Sep 9, 2010
    Posts:
    967
    For nonalloc API, you need to allocate & instantiate the result array (3rd parameter) yourself first. This way the API doesn't need to allocate new array for every call and you can reuse your own array. This is good for performance/memory. Thus results.Length in your case is 2, because you have initialized the array size to be 2, not because API is returning 2 results.

    In more laymen terms, this means that you are saying "The maximum amount overlaps that I care about is 2, and I'm getting better performance for it".

    Code (csharp):
    1.  
    2. const int maxOverlaps = 2;
    3.  
    4. Collider2D[] overlaps = new Collider2D[maxOverlaps]; // You should do this outside the method so you can re-use the array, but I'm putting it here for examples sake.
    5.  
    6. int result = OverlapAreaNonAlloc(pointA, pointB, overlaps);
    7. for(int i=0; i<result; i++)
    8. {
    9.     Collider2D overlap = overlaps[i];
    10.     Debug.Log("Overlapping with: " + overlap.gameobject.name);
    11. }
    12.  
     
    Last edited: May 12, 2015
  3. Deleted User

    Deleted User

    Guest

    "Thus results.Length in your case is 2, because you have initialized the array size to be 2, not because API is returning 2 results."

    That's it! I appreciate you clearing it up!