Prefab Collider2D is not recognized as Raycast Collider

Hello everyone :) Here is the situation:

I have a baddy prefab that has two collider components: a simple CapsuleCollider2D used for physics, and a PolygonCollider2D trigger used only for muscle collisions.

PolygonCollider2D is updated via the attached script (Baddy.cs) only if necessary, 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 bad practice, but it does its job. It works great: in the scene of the game, I can pause and see that there really is a collider polygon on our baddy prefab.

In another attached script (CollisionHandler.cs) we test the mouse click 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 to be false, although I could print both hit.collider and this.gameObject.GetComponent<PolygonCollider2D>() immediately before our if(MousePress()) command if(MousePress()) and designate them as:

  D_Prefab(Clone) (UnityEngine.PolygonCollider2D) 

They cannot be different PolygonColliders, because there can only be one at a time, since our Baddy script removes and creates PolygonCollider at a time.

Any ideas what could be wrong?

+5
source share
1 answer

Using Physics2D.RaycastAll with layerMask, I solved the problem with other colliders that were in the way, including baddy own capsuleCollider2D. Fortunately, my baddys will freeze before I need to check for mouse conflicts, so I updated the collider ahead of time when the baddy anim speed was 0. Obviously, creating and deleting colliders using the update function does not give the system enough time to process collisions.

http://answers.unity3d.com/questions/1326583/prefab-collider2d-not-recognized-as-raycast-collid.html#comment-1327337

+2
source

Source: https://habr.com/ru/post/1265526/


All Articles