Raycast sometimes returns nil

Hello fellow developers!

I am currently having trouble with a game city building game similar to “kingdoms and castles” but I have come across a raycasting problem.

im trying to fire a raycast up from each grid to check if there is anything on top of it (like a tree or a rock), but this only works sometimes

this is my code that runs inside of a server script:

for i, turrain in pairs(script.Parent:GetChildren()) do
	if turrain:IsA("BasePart") then
		wait(0.1)
		local params = RaycastParams.new()
		params.FilterDescendantsInstances = {workspace.Turrain.Rocks}
		params.FilterType = Enum.RaycastFilterType.Exclude
		local cast = workspace:Raycast(turrain.Position, turrain.CFrame.UpVector.Unit * 100, params)
		if cast then
			if cast.Instance then
				if cast.Instance.Parent.Name == "Trees" then
					turrain.HoldingTree.Value = true
				else
					print(cast.Instance.Parent.Name)
				end
			else
				print("no instance")
			end
		else
			print(cast)
		end
	end
end
print("done!")

i have 192 tiles for testing and a random amount of tiles error. this is usually around 60-100 tiles

image
in this example it is 96.

if anybody has a solution to this, it would be very appreciated if you could tell me i have been working on this for hours :sob:

thank you!

nil just means that there is nothing detected in the raycast, so there would be nothing above it!

Also, for direction, you may just be able to do like Vector3.new(0, 100, 0) instead of UpVector stuff

1 Like

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