Hello everyone :) Here's the situation:
I have a baddy prefab which has two collider components: a simple CapsuleCollider2D used for physics, and a trigger PolygonCollider2D used only for mouse point collisions.
The PolygonCollider2D is updated through an attached script (Baddy.cs) only when needed using:
if(this.gameObject.GetComponent<PolygonCollider2D>()!=null){
Destroy(this.gameObject.GetComponent<PolygonCollider2D>());
}
this.gameObject.AddComponent<PolygonCollider2D>();
this.gameObject.GetComponent<PolygonCollider2D>().isTrigger=true;
Yes, this is poor practice, but it get's the job done. It works perfectly: in the scene view of the game I can pause and see that there is indeed a polygon collider on our baddy prefab.
In another attached script (CollisionHandler.cs) we check for a mouse press on our baddy:
if(MousePress()){
hit=Physics2D.Raycast(level.mousePoint, Vector2.zero, 0f);
if(hit&&hit.collider==this.gameObject.GetComponent<PolygonCollider2D>()){
print("baddy mousePress");
}
}
However hit.collider==this.gameObject.GetComponent<PolygonCollider2D>()
turns out false, even though I could print both hit.collider
and this.gameObject.GetComponent<PolygonCollider2D>()
immediately before hand in our if(MousePress())
and have them both defined as:
D_Prefab(Clone) (UnityEngine.PolygonCollider2D)
They couldn't be different PolygonColliders because there can only be one at a time, since our Baddy script removes and creates the PolygonCollider simultaneously.
Any ideas what could be going wrong?
By making use of Physics2D.RaycastAll with a layerMask, I resolved the issue of other colliders getting in the way, including the baddy's own capsuleCollider2D. Fortunately, my baddys would freeze before I needed to check for mouse collisions, so I updated the collider ahead of time when the baddy's anim speed was 0. Evidently creating and removing the colliders through an update function doesnt give the system enough time to handle the collisions.
http://answers.unity3d.com/questions/1326583/prefab-collider2d-not-recognized-as-raycast-collid.html#comment-1327337
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With