Need help getting a script attatched to multiple objects perform its function on only one at a time

im trying to have a constant raycast to detect what tile the mouse is hovered over to activate a child gameobject which displays a highlight graphic. The ray works but it activates every tiles highlight instead of just the tile touched by the mouse, how do i make it activate a specific tiles highlight? It needs to be a ray because the detection needs to pierce through multiple gameobjects whereas OnMouseEnter only detects the top one.

code to create the ray

public RaycastHit2D tileRay;
public LayerMask tile;

void Update()
{
tileRay = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, tile);
}

and this is what i believe is the problem code which is in a seperate script attatched to the tile prefab

[SerializeField] private GameObject highlight;
public GameObject mainCam;


void Start()
{
    mainCam = GameObject.Find("Main Camera");
}

void Update()
{
    RaycastHit2D tileRay = mainCam.GetComponent<CameraController>().tileRay;

    if (tileRay.collider != null)
    {
        highlight.SetActive(true);
    }
}

working with little unity knowledge and cant find other sources that apply to my problem, thanks!

OnMouseEnter

Your wording is rather imprecise.
“it activates every tiles highlight”, do you mean all of them at once, not actually just the one pointed at? Or do you mean that if you move the mouse across multiple tiles the all STAY highlighted?

In case of the later, you can just remember the last tile highlighted by the object reference and unhighlight it as soon as a different tile is hit.

it does both, i was going to do the second part after i figured out the first. how would i do what you suggested?

Sorry if that spunds harsh but you might want to start some structured programming tutorial, because this is rather trivial and you will encounter many many similar and harder problems on your journey as a gamedev :wink:
But you are in luck, ChatGPT makes learning easier today than ever before!

Store the object in a variable of your raycaster of type GameObject. Essentially what you did with mainCam. Then in the successful raycast, first disable the object in that variable if not null, then assign it to the newly highlighted object instead.