How to make a touch raycast detection for lots of parts at once

Im trying to make a group of models with lots of parts inside of that model that shoot out a ray facing forward that detect when either of them are touched by a certain group of parts which are in a folder inside workspace. Im not sure if i should use collectionservice or what, also these models will be despawning and spawning time to time by the players if that makes a difference to the script. And I would like to offset the ray from the part inside the model. The model and parts inside will be moving a lot and changing direction too. but I need someone to point me in the right direction.

local RunService = game:GetService("RunService")
local CollectionService = game:GetService("CollectionService")

local ModelsFolder = game.Workspace.Models

local connection

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
raycastParams.FilterDescendantsInstances = {}


for _, model in pairs(ModelsFolder:GetChildren()) do
	for _, part in pairs(model.Parts:GetChildren()) do
		function SensorPostSimulation(step)
			local rayPart = Instance.new("Part")
			rayPart.Anchored = true
			rayPart.CanCollide = false
			rayPart.CanQuery = false
			rayPart.CanTouch = false
			rayPart.Shape = Enum.PartType.Ball
			rayPart.Size = Vector3.one
			rayPart.Parent = workspace

			local Origin = bogie.Spine

			local DetectedSensor = workspace:Raycast(Origin.Position, Origin.CFrame.LookVector * 50, raycastParams)

			if DetectedSensor then
				local Face = DetectedSensor.Normal
				local HitPosition = DetectedSensor.Position

				rayPart.Position = HitPosition
			end
		end
	end
end

connection = RunService.Heartbeat:Connect(SensorPostSimulation)
1 Like