Make my player activate objects around it using RayCastHit2D


Hello, to make this as brief as possible, I have my player character in the middle and he’s shooting out 2 blue rays in each direction. What I want is for each “numbered rectangle” that is affected by those rays to be “activated”. For example, in the photo above, rectangles 2, 3 and 4 should be active, while 1 and 5 are off.

Note: each of the rectangles is a child of the ground below it, and has its own hitbox with “Is trigger” enabled.

Currently the code I have for this is
in the Player script:

    RaycastHit2D RayRight = Physics2D.Raycast(transform.position, Vector2.right, SpawningRange, SpawningRegion);
    RaycastHit2D RayLeft = Physics2D.Raycast(transform.position, Vector2.left, SpawningRange, SpawningRegion);

    if (RayRight)
    {
        GroundBehavior groundRight = FindObjectOfType<GroundBehavior>();
        groundRight.SetActive();
    }

What this does is define both the right and left rays, and is supposed to detected the colliders of what it’s hitting, but instead this is activating the boolean of 5. Which is obviously not being hit.

in the Ground Script:

using UnityEngine;

public class GroundBehavior : MonoBehaviour
{
    public bool isActive;
    public void SetActive()
    {
        isActive = true;
    }
    public void SetOff()
    {
        isActive = false;
    }
}

Here I just have the boolean being switched on and off.
I had some luck activating either all of them, or just one random one, but I’m trying to activate (then deactivate) only the ones hit by the raycast. Thanks.![alt text][2]

You have multiple issues in your code

  1. You are using the version of Raycast that only return the first collision encounter. You want to use Physics.RaycastAll [1]
  2. FindObjectOfType() will find the first object of type GroundBehaviour. [2]
  3. The raycast will not detect any object it originate from. “Notes: Raycasts will not detect colliders for which the raycast origin is inside the collider.” [1]
  4. You will only turn on your region, but never turn them off.

You do not need to do raycasts to determine which region most be activated. Use the distance and the size of each region.


[1] Unity - Scripting API: Physics2D.RaycastAll

[2] Unity - Scripting API: Object.FindObjectOfType