In the unity 2D api there is a **Collider2D.IsTouching** and **Collider2D.IsTouchingLayers** methods, but there no such method for the 3D Collider, Why?
This really useful for checking if player is grounded with one line of code:
Unity uses third party packages for both 2D and 3D physics. For 2D, the underlying physics is driven by Box2D, while for 3D, NVidia’s PhysX is used.
So the things you have access to in your C# code is essentially wrappers for calls to those two libraries, or whatever Unity has bolted on top of those. I’m assuming that Box2D has an IsTouching call, while PhysX doesn’t.
Now, I imagine that collider.IsTouching doesn’t exist because it would be somewhat expensive. Either you’d have to have a list of all the things everything touches (which would cost TONS of memory, and make the library useless), or you’d have to scan the object for overlaps, which would probably be very slow.
Essentially, if the method existed, the docs would probably state “you should not use this in Update, because it’s super-slow”. OnCollisionEnter/Exit does not have any of those drawbacks, so.
2D checks for overlaps are probably a lot faster (I’d imagine by an order of magnitude), so it’s viable to have an IsTouching method.
I know this is old, but re: “you’d have to have a list of all the things everything touches (which would cost TONS of memory …)”- I think it MUST already do that?
Otherwise, how does it possibly know to call onTriggerEnter and onTriggerExit? (Both of those mark a transition of states, meaning you have to know the previous AND the current state to detect it- ie, a “list of all the things everything (currently) touches”).
I don’t actually know the underlying code, so maybe there’s some clever trick that gets around this? But this constraint (requiring current state) feels pretty airtight…
Anyways- the point of the question was “WHY is there no colliderIsTouching”.
One answer: bc the underlying physics implementations don’t have such an API. (Which just kinda launders the question? Like, why doesn’t the underlying physics implementation offer it? Why hasn’t unity built one on top of the underlying physics implementation? Why not, at the very least, just expose that list which it surely must be storing somewhere [I’m like, 95% confident hah]?)
Another answer: bc it would be slow. But that’s pretty… relative? Like you don’t want a physics world built on one-off collision detection. But often, there’s a conditional tree behind needing to detect 3d collision for one frame on one pair of objects, and managing some physics heirarchy for that is slow, error prone, and unnecessarily complex!
tl;dr: the current answer for “why” might be correct, but it’s not exactly satisfactory. If there exists a reason that takes into account these listed concerns, I’d love to hear it!