Does if raycast then only fire when the raycast hits something?

So I have a script that sends a raycast. But I have a question about it.

heres the code

		local raycast = workspace:Raycast(po1,direction)
		
		if raycast then
			
		end

So anyhow, the part Im talking about is the:

if raycast then

Does this fire when the raycast hits something? Or when the raycast is made?
Thanks!

workspace:Raycast only return a RaycastResult when it gets intersected by a valid object.

Therefore, it will only exist if the ray hits something.


Here’s an example bit of code:

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

local camera = workspace.Camera

local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {character}
params.IgnoreWater = false
params.RespectCanCollide = true

local raycast = workspace:Raycast(camera.CFrame.Position, camera.CFrame.LookVector * 10, params) --// This will only be equal to something if the raycast hits something

if raycast then
	print("Raycast hit something:", raycast --[[prints all of the data in the RaycastResult (i.e. Instance, Position, etc.)]])
	if raycast.Instance:IsA("BasePart") then
		raycast.Instance.BrickColor = BrickColor.new("Really red")
	end
else
	print("Raycast did not hit an object")
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.