How can I detect if an object is behind a wall

I am making an interaction system which works but if anything is behind the wall then the script tries to go to it and activate so to prevent than I wanna know if there is a way from these types of things from happening.

I don’t know what is considered a wall in your game but you can cast a ray in a forward direction and if it’s a wall then you can just ignore it or do something else

Just cast a ray from your characters root part to the object, and if the ray hits something along the way, the object is obscured and cannot be interacted with.

How do I cast a ray to an object?

Why not check out the api reference for it.

Create a ray at the position of the root part, with the direction vector towards the object. You can get the direction vector like so:

CFrame.new(Root.Position, Object.Position).LookVector

Then, get the magnitude (distance) between the root part and the object. Multiply the ray’s direction by that value, and it will cast the distance between the root and the object.

P.S. Don’t forget to ignore the character when using :FindPartOnRay().

You can create a new ray using Ray.new

local myRay = Ray.new(Orgin.Position, Direction.Position/CFrame)

Casting it would also be simple.

local hit, pos = workspace:FindPartOnRay(myRay)

You’ll have to do the rest on your own my friend.

But I already have nearest distance done already

If you already have the distance, then just multiply the ray’s direction by the distance you have.