Hi, I need to shot a ray from the enemy to the player and it should ignore all the enemies(and prefab bullets) it touches. Though it should detect things like ground or walls to know if the player is "visible" from the perspective of the enemy who shot the ray. E.g.: EnemyWhoShotTheRay spotted the player: Player <------- Enemy ------- EnemyWhoShotTheRay EnemyWhoShotTheRay did not spotted the player: Player _____ Wall <-------- Enemy -------- EnemyWhoShotTheRay I'm not used to using raycast so I'm sure some things could be improved. Here's my code: Code (CSharp): private List<Transform> inDetectionRange = new List<Transform>(); private IEnumerator CheckDetectionRange() { while(inDetectionRange.Count != 0) { for (int i = 0; i < inDetectionRange.Count; i++) { RaycastHit2D hit = Physics2D.Raycast(transform.position, inDetectionRange[i].position - transform.position, maxDistance, 11); Debug.DrawRay(transform.position, inDetectionRange[i].position - transform.position, Color.red); Debug.Log(hit.collider.name); } yield return new WaitForSeconds(1); } hasStartedDetection = false; ... ... } I think the issue is that I'm setting the layers wrong, what I understood is that I should put the int of the layer which I want the ray be part of, something like assigning the raycast layer(so that i assigned the ray to layer 11, which ignore collision with enemies and bullets). And I think the problem is with layers because while running it return this error: NullReferenceException: Object reference not set to an instance of an object, referencing the Debug.Log(hit.collider.name), so the ray wouldn't be hitting anything by what I understand. If I don't set any layer it works (having unchecked the Queries Start In Colliders box), but the ray collides with the first thing it touches, being or not an enemy. Any suggestion is appreciated, thanks!
Exactly instead of (..., maxDistance, 11) write (..., maxDistance, 1 << 11), it is because layer mask is not a layer number it is a Bitmasks. or you can get layer mask with multiple of your layer names like this LayerMask.GetMask("UserLayerA", "UserLayerB")
Thank you! I did not know that they work that way. I chose layer 11 because it ignores collisions with enemies and bullets but instead, I should use 1<<8 | 1<<9 which are the layers assigned to player and scenario respectively so that I'm sure the ray only collides with the player and all the objects that belong to the scenario. Thanks again, and have a good day!