0
\$\begingroup\$

I am writing some logic to handle spawning objects into a game scene at a randomly generated location based on the size of a collider's bounds. The logic for getting the coordinates and instantiating an object in the corresponding location is working fine but I have logic I use to make sure that the object being placed is not colliding with any other colliders. To detect if the gameobject I have placed is colliding with anything I am using Physics2D.OverlapCollider(), passing in the collider of the gameobject. I get no colliders back though. Below is a simplified version of what I'm doing:

var x = UnityEngine.Random.Range(xmin, xmax);
var y = UnityEngine.Random.Range(ymin, ymax);
var spawnedObjCollider = spawnedObj.GetComponent<Collider2D>();
spawnedObj.transform.position = new Vector3(x, y, 0f);
Physics2D.SyncTransforms();

var overlappingColliders = new List<Collider2D>();
var numColliders = Physics2D.OverlapCollider(spawnedObjCollider, new ContactFilter2D().NoFilter(), overlappingColliders);

In the case that I'm looking at, the spawned gameobject is overlapping another collider but it acts like it doesn't see it. Both objects are on the default layer even though it shouldn't matter what layer they are on since I am passing in NoFilter(). (the small collider is the collider of the spawned object):

enter image description here

These are the collider settings, at runtime, for the spawned gameobject:

enter image description here

These are the collider settings, at runtime, for the collider that the spawned gameobject is being put on top of:

enter image description here

\$\endgroup\$
3
  • \$\begingroup\$ Do you get different results with OverlapBox / OverlapArea? or their All/NonAlloc versions? \$\endgroup\$
    – DMGregory
    Sep 22 at 16:07
  • \$\begingroup\$ So...I added back the Physics2D.SyncTransforms() and restarted unity and now it works. Welp \$\endgroup\$
    – sabo
    Sep 22 at 16:09
  • \$\begingroup\$ Maybe you accidentally synced the 3D physics transforms by leaving out the 2D part in your first attempt? In any case, want to share that as an answer? \$\endgroup\$
    – DMGregory
    Sep 22 at 16:11

1 Answer 1

0
\$\begingroup\$

I must not have had Physics2D.SyncTransforms(); set correctly in my code after the position was changed. Adding that seemed to fix the issue.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .