Why wont my ray avoid accessories

I am making a gun, but then i realised that when the ray hits accessories it does no dmg, so I did what i thought would work but then it gave me a attempt to index nil with ‘IsA’ error.

This is the script

game.ReplicatedStorage.Gun2FireEvent.OnServerEvent:Connect(function(player, bulletOrigin, mousePosition, gun, mouse)
	local rayCast = Ray.new(bulletOrigin, (mousePosition - bulletOrigin).unit * 100)
	local blacklist = {player.character}
	local hit, noPosition, Normal = game.Workspace:FindPartOnRayWithIgnoreList(rayCast, blacklist, false, true)
	if hit:IsA("Accessory") then
		table.insert(blacklist, hit)
	end

Well where is it supposed to take dmg?
Shouldnt you add something like health = health -50

Make sure to use a if statement to detect if hit is nil before calling :IsA() on it.

if hit ~= nil then
    if hit.Parent:IsA("Accessory") then
		table.insert(blacklist, hit)
	end
end

Also, you can’t “hit” accessories with Ray’s. You can only hit their mesh parts, so you will have to check the parent of the hit for being a accessory.

1 Like

It doesn’t hit the accessory itself, it hits the parts inside the accessories.

5 Likes

I managed to get the accessories into the ignore list, but the accessories are still preventing the player from taking dmg.

The new script

game.ReplicatedStorage.Gun2FireEvent.OnServerEvent:Connect(function(player, bulletOrigin, mousePosition, gun, mouse)
	local rayCast = Ray.new(bulletOrigin, (mousePosition - bulletOrigin).unit * 100)
	local blacklist = {player.character}
	local hit, noPosition, Normal = game.Workspace:FindPartOnRayWithIgnoreList(rayCast, blacklist, false, true)
	if hit ~= nil then
		if hit.Parent:IsA("Accessory") then
		table.insert(blacklist, hit.Parent.ClassName)
		end
	end

The issue is that you insert the accessory parts into the blacklist after calling :FindPartOnRayWithIgnoreList, instead loop through every player before calling it and insert their accessories into the blacklist.

game.ReplicatedStorage.Gun2FireEvent.OnServerEvent:Connect(function(player, bulletOrigin, mousePosition, gun, mouse)
	local rayCast = Ray.new(bulletOrigin, (mousePosition - bulletOrigin).unit * 100)
	local blacklist = {player.character}
	
	for _,plr in pairs(game:GetService("Players"):GetPlayers()) do
		if plr.Character then
			for i,v in pairs(plr.Character:GetChildren()) do
				if v:IsA("Accessory") then
					table.insert(blacklist, v.Handle)
				end
			end
		end
	end
	
	local hit, noPosition, Normal = game.Workspace:FindPartOnRayWithIgnoreList(rayCast, blacklist, false, true)
end)
1 Like