How can a part check if a ray is hitting it or not?

I’ve been thinking about this for a while, and I cannot seem to figure out how I can implement this. Obviously, you have to check for the RaycastResult.Instance, but once the ray is off the object, there’s no way I can check for that specific block.

What I’m trying to accomplish is a “Delete Mode” for my Building system, where the object you want to delete is highlighted(the color is changed to) red. However, I need to check if the ray is off, so I can revert it back to it’s normal color.

local lastPart, lastColor

-- raycast func
local currentPart = RaycastResult.Instance
if currentPart ~= lastPart then -- moved to a diff part
    lastPart.Color = lastColor -- set color of last remembered part to the last remembered color (original color)
    lastPart = currentPart
    lastColor = currentPart.Color -- remember new color
    currentPart.Color = Color3.new(1, 0, 0)
end
2 Likes

Oh sorry, I should’ve came back, this doesn’t work, the part is still red after the ray is off.

The logic I showed you worked fine for me, maybe you didn’t implement it correctly

local Camera = workspace.CurrentCamera
local LocalPlayer = game:GetService'Players'.LocalPlayer
local Mouse = LocalPlayer:GetMouse()
local lastPart, lastColor

game:GetService'RunService'.RenderStepped:Connect(function()
	local Params = RaycastParams.new()
	Params.FilterDescendantsInstances = {LocalPlayer.Character}
	local RaycastResult = workspace:Raycast(Camera.CFrame.Position, Mouse.UnitRay.Direction * 500, Params)
	if RaycastResult then
		local currentPart = RaycastResult.Instance
		if currentPart ~= lastPart  then -- moved to a diff part
			if lastPart then
				lastPart.Color = lastColor -- set color of last remembered part to the last remembered color (original color)
			end
			lastColor = currentPart.Color -- remember new color
			lastPart = currentPart
			currentPart.Color = Color3.new(1, 0, 0)
		end
	end
end)

Yeah, I did something similar to that, but it caused all of the blocks to be set to one color. Fixed it. Thanks.