Using Raycast To Detect GameObjects in Unity3D
Objective: Enemies that move straight down the Y-axis can detect laser shots made by the player.
Step 1: In Unity, select the Laser Prefab in the Project window and create a new Layer in the Inspector window called Laser.
Step 2: Set the Layer for the Laser Prefab and the Triple Shot Prefab to Laser.
Step 3: In the Enemy script, create two private RaycastHit2D variables called _laserDetectionLeft and _laserDetectionRight. Then create a private float variable called _raycastLength and have it equal 0.5f.
Step 4: Create a private method called LaserDetectionRaycast(). Within this method, create an int variable called _layerMask and have it equal to 1 << 6. Since Layers are designated through an integer bitmask, the formula of 1 << 6 shifts the bit up and reflects that the #6 layer, which is the Laser layer, is the layer assigned to the _layerMask variable. This is also why there are only 32 available Layer Mask options.
Step 5: Using the _laserDetectionLeft variable, have it equal to Physics2D.Raycast, with a position of the Enemy Prefab on the X-axis, but -2 less than the Y-axis position so the detection will happen in front of the Enemy Prefab. Then set the direction of the Raycast to be horizontal and to the left of the Enemy Prefab’s center position on the X-axis by using Vector2.left. Then set the length of the Raycast to the _raycastLength variable and set the layer the Raycast should detect to the _layerMask variable.
Step 6: To make the Raycast visible in the Scene view, use Debug.DrawRay with the same position information from the previous statement, then multiply the Raycast direction and the Raycast length, and set the color of the ray to red.
Step 7: To test that the detection is working, create an if statement stating that if the _laserDetectionLeft Raycast detects a collider that is not equal to null, then display the name of the GameObject the collider was attached to in the Console window. Lastly, call the LaserDetectionRaycast() method in the EnemyMovement() method within the else statement, which is then called within the Update() method.
Save the script, go back into Unity and the Raycast should only detect GameObjects that use the Laser layer.
Step 8: Repeat the process for the _laserDetectionRight variable but use Vector2.right as the Raycast direction.