How to have an object with rigidbody touch another object with isTrigger true
Hello all!
I'm having a bit of an issue with two objects hitting each other. I am probably not doing this the correct or the most efficient way, but I have two objects. One (which is object pooled) moves along the X axis, deleted when it gets to a certain point, and re-spawned. Kind of like a conveyor belt. This object only has a box collider with isTrigger checked. The other object is below it and has both a box collider and a rigidbody. This moves on the y axis.
When I test it out, it passes through, which is what I want, but it doesn't call the onCollisionEnter2d function.
Is there a way for these two objects to phase through each other, and still alert the functions?
void OnCollisionEnter2D (Collision2D other) {
if (this.gameObject.tag == "conveyorItem")
{
Debug.Log("CorrectTag");
if (other.gameObject.tag == "shootItem")
{
Debug.Log("Hit!");
}
}
}
Answer by Matthewj866 · Apr 20, 2017 at 08:57 PM
Hi there @Bindlestick
Unfortunately due to the collision type, OnCollisionEnter2D
will never be called - instead, you should either:
make the one with OnTriggerEnter2D
one call a public method on the other object, e.g.:
if (other.tag == "whatever the tag is called")
{
other.GetComponent<OtherMonoBehaviour>().DoSomething();
}
OR
Convert both into regular colliders so OnCollision2D()
gets called, also change the OnTriggerEnter2D()
call on the object with the trigger collider to OnCollision2D()
to account for the collider type change.
Hope this helps!
Thanks for your reply @$$anonymous$$atthewj866. Appreciate the help!
Just making sure I'm understanding correctly, since I am still very green at Unity. The first option, when you say onTriggerEnter2D, am I replacing the onCollisionEnter2D with onTriggerEnter2D?
The first option requires no method name change, assu$$anonymous$$g OnTriggerEnter2D()
is already being called by the $$anonymous$$onoBehaviour
with access to the trigger collider. If you have defined the method with the wrong name, then you are correct - you will need to change the name to OnTriggerEnter2D()
.
Documentation: https://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.OnTriggerEnter2D.html
Hope this solves your problem! And please remember to mark this as the correct answer if it does.