Why won't my raycast script work?

I’m trying to make it so a ray is casted all the time, and if a player comes in contact with it, it deals damage to them. It won’t work for some reason, wont even throw an error, could someone please help?

–Script inside of part

local origin = script.Parent.CFrame.LookVector * 300
local destination = script.Parent.Parent.Finish.Position
local direction = destination - origin

while wait() do
	local raycast = workspace:Raycast(origin, destination)
	if raycast then
		if raycast.Instance:FindAncestorOfClass("Model") then
			if raycast.Instance:FindAncestorOfClass("Model"):FindFirstChild("Humanoid") then
				raycast.Instance:FindAncestorOfClass("Model"):FindFirstChild("Humanoid").Health -= 30
			end
		end
	end
end```

You need to add raycast params to the workspaace:Raycast function.

You did :FindAncestorOfClass do

if raycast.Instance.Parent:IsA("Model") then
	if raycast.Instance.Parent:FindFirstChildWhichIsA("Humanoid") then
		-- do stuff
	end
end

Try changing to the following:

  • local origin = script.Parent.Position
  • local direction = (destination - origin).Unit * 300

Also, I would change while wait() do to a RenderStepped function for better performance.

1 Like

I’m pretty sure you don’t, it says it’s optional.

Thanks for the response, I’m currently using a server script, can’t RenderStepped only be used on the client?

FindAncestorOfClass() isn’t a valid function, you were likely trying to use:

https://developer.roblox.com/en-us/api-reference/function/Instance/FindFirstAncestorOfClass

FindFirstAncestorOfClass() instead.

local origin = script.Parent.CFrame.LookVector * 300
local destination = script.Parent.Parent.Finish.Position
local direction = destination - origin

while wait() do
	local raycast = workspace:Raycast(origin, destination)
	if raycast then
		if raycast.Instance:FindFirstAncestorOfClass("Model") then
			if raycast.Instance:FindFirstAncestorOfClass("Model"):FindFirstChild("Humanoid") then
				raycast.Instance:FindFirstAncestorOfClass("Model"):FindFirstChild("Humanoid").Health -= 30
			end
		end
	end
end

These are the other 2 ancestor related functions shared by all instances:
https://developer.roblox.com/en-us/api-reference/function/Instance/FindFirstAncestor
https://developer.roblox.com/en-us/api-reference/function/Instance/FindFirstAncestorWhichIsA