Filter certain materials when casting ray

I want a ray to filter and go through parts made of certain materials, however raycastParams.FilterDescendantsInstances = {Enum.Material.Plastic}
errors with “Unable to cast value to object”.

What other options are there in filtering through parts made of certain materials?

1 Like

You could use CollectionService as 1 of the other posts mentioned earlier?

I’m assuming you mean using it in combination with FindPartOnRayWithIgnoreList(), which has been deprecated?

Yes, but I don’t know any other alternates other than this since the modern Raycast is only capable of detecting Material types when a Result has been found

Fire a normal ray, if it hits a part → check the material.
If it’s a “ignore” material → Add part to FilterDescendantsInstances, fire another ray continuing from last.

Repeat until you hit a valid material or the distance you want to check has been passed

Except inserting the part into FilterDescendantsInstances doesnt work and the new raycast instance still prints out the part?

		if string.find(tostring(raycastResult.Instance.Name), "Plastic") then
			table.insert(raycastParams.FilterDescendantsInstances, raycastResult.Instance)		-- Insert part into ignore table
			local EndPos = RayOrigin + RayDirection * RayDirection.Unit
			local NewRayTarget = player.Character.HumanoidRootPart.Position
			local NewRayDirection = (NewRayTarget - EndPos)
			local NewRayResult = workspace:Raycast(EndPos, NewRayDirection, raycastParams)
			if NewRayResult then
				print(NewRayResult.Instance)
			end
		end

Alright I figured it out.
Use @greenboo5 method. However, add the part to another table, and set raycastParams.FilterDescendantsInstances to that table.

This is a good solution, although it is a bit complicated to implement.

A simpler solution is to use Collision Groups and the RaycastParams.CollisionGroup property.

1 Like