Trying to Make a Visual Ray Cast but it isn't Working

I am trying to make a game that includes a gun and I want there to be a part that acts as the trail of the Ray Cast. The problem is that the part isn’t spawning when it is supposed to.
I have tried to look at videos and posts on the developer hub but they all say to do what I have done.

Here is the script:

script.Parent.Fire.OnServerEvent:Connect(function(player,mousePos)

	local raycastsParams = RaycastParams.new("Params")
	raycastsParams.FilterDescendantsInstances = {player.Character}
	raycastsParams.FilterType = Enum.RaycastFilterType.Blacklist

	local raycastResult = workspace:Raycast(script.Parent.Shoot.Position, (mousePos - script.Parent.Shoot.Position)*300, raycastsParams)

	if raycastResult then
		
		local distance = (script.Parent.Shoot.Position - raycastResult.Position).Magnitude
		local p = Instance.new("Part")
		p.Name = ("Gun Trail")
		p.Anchored = true
		p.CanCollide = false
		p.Transparency = 0.5
		p.Size = Vector3.new(0.1, 0.1, distance)
		p.CFrame = CFrame.lookAt(script.Parent.Shoot.Position, raycastResult.Position)*CFrame.new(0, 0, -distance/2)
		
		local hitPart = raycastResult.Instance
		local model = hitPart:FindFirstAncestorOfClass("Model")
	
		if model then
			if model:FindFirstChild("Humanoid") then
				model.Humanoid.Health -= 30
			end
		end
	end
end)

I was just wondering if anyone knew what the issue was and a way for me to fix it. Thanks! :grin:

Looking at your script, I think the issue is that you forgot to parent the part to workspace (which would make it visible).
The “Instane.new()” function has a Parent parameter which you can use
So basically change Instance.new(“Part”) to Instance.new(“Part”, game.Workspace)

1 Like

Thank you! I thought it was something that had to do with it not being in the workspace I just didn’t know how to put it there. :+1:

Never do (“Part”, game.Workspace), it is terrible for performance. Do Part.Parent = workspace.

1 Like

Why would you use the Instance.new parent argument? It’s best to not use the parent argument if you care about performance. A Roblox staff explained this: PSA: Don't use Instance.new() with parent argument

1 Like

Okay, thank you for this tip, it does seem a little more efficient.