Raycasting Issue... attempt to index nil with 'Instance

I am trying to use raycasting to know when a certain model has reached a certain point. But script Editor is saying "attempt to index nil with ‘Instance’ " I have looked on the dev forum but none have seemed to be exactly what I am looking for.

local part = script.Parent
local Roller = workspace.RollerCoasterStageOne
local serverstorage = game:GetService("ServerStorage")
local rollerstopper = serverstorage.RollerStopper
local RollerClone = serverstorage.RollerCoasterStageOneC


local origin = part.Position
local direction = part.CFrame.LookVector* 100

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {Roller, RollerClone}
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist

local raycastResult = workspace:Raycast(origin, direction, raycastParams)


if raycastResult.Instance == Roller then -- Happens here
	local model = rollerstopper:Clone()
	model.Parent = workspace
	local rollerstopperc = RollerClone:Clone()
	rollerstopperc.Parent = workspace
	
end
2 Likes

It’s because your raycast found nothing, so you have to do if raycastResult and raycastResult.Instance == Roller then I believe, also your thing is going to work once since it’s not looped

5 Likes
if raycastResult ~= nil then
    if raycastResult.Instance == Roller then
	   local model = rollerstopper:Clone()
	    model.Parent = workspace
	    local rollerstopperc = RollerClone:Clone()
	    rollerstopperc.Parent = workspace
    end
	
end
4 Likes