When there was nothing to do, I found the Raycast function of the class Collider2D in unity . I wondered where the beam would start from (I thought that from all points of the collider). I decided to test it, wrote the code, and as a result, the collision displays nothing. Why is that? And where are the rays coming from? Here is the test script code:

  private Collider2D collider2d; private void Start() { collider2d = GetComponent<Collider2D>(); } private void Update() { RaycastHit2D[] hits = null; collider2d.Raycast(Vector2.left, hits); Debug.Log(hits == null ? "No collusion" : hits.ToString()); } 

But the screen itself test: enter image description here

I tried to do the same conclusion:

 RaycastHit2D[] hits = null; Debug.Log(collider2d.Raycast(Vector2.left, hits)); 

As a result, the identity itself, only displays "0"

  • "Casts a ray into the collider position". Probably there are no more colliders on the scene or do not get in the way. - Valera Kvip

1 answer 1

This code will show you the first three colliders encountered.

 private void Update() { // массив ΠΏΠΎΠ΄ Ρ‚Ρ€ΠΈ попадания RaycastHit2D[] hits = new RaycastHit2D[3]; collider2d.Raycast(Vector2.left, hits); print("~~~~~~ Π½Π°Ρ‡Π°Π»ΠΎ ΠΏΠΎΠΏΠ°Π΄Π°Π½ΠΈΠΉ ~~~~~~~~"); foreach (RaycastHit2D hit in hits) { print(hit.collider); } print("~~~~~~ ΠΊΠΎΠ½Π΅Ρ† ΠΏΠΎΠΏΠ°Π΄Π°Π½ΠΈΠΉ ~~~~~~~~"); } 

The fact is that unlike the 3D version, which has the RaycastHit parameter with the out keyword, in the 2D version, hits are an array, plus without out, the array should already be initiated. Setting instead of null an array of three elements, we get the first three hits in this direction.