Raycast Not Visualizing

Hello.

I was trying to make a gun using raycasting.
I was following a tutorial by Threasto.
For some reason it wont Visualize the raycast.
What I mean by this is that the script wont create a part when I shoot the weapon.

Heres the code:

--Services
local replicatedStorage = game:GetService("ReplicatedStorage")
local debris = game:GetService("Debris")

--Variables
local remoteEvent = replicatedStorage.ToolRemote
local visualsFolder = game.Workspace.Visuals

local function createVisual(startPositon, direction)
	local center = startPositon + direction / 2
	local distance = direction.Magnitude
	
	local visual = Instance.new("Part")
	visual.Parent = visualsFolder
	visual.Anchored = true
	visual.CanColilide = false
	visual.BrickColor = BrickColor.new("Gold")
	visual.Material = Enum.Material.Neon
	
	visual.CFrame = CFrame.new(center, startPositon)
	visual.Size = Vector3.new(0.1, 0.1, distance)
	
	debris:AddItem(visual, 0.1)
end

remoteEvent.OnServerEvent:Connect(function(player, tool , startPosition, endPosition)
	local maxRange = tool:GetAttribute("MaxRange")
	local damage = tool:GetAttribute("Damage")
	local headshotDamage = tool:GetAttribute("HeadshotDamage")
	local gunShot = tool.Shoot
	
	gunShot:Play()
	
	local direction = (endPosition - startPosition).Unit * maxRange
	
	local raycast = game.Workspace:Raycast(startPosition, direction)
	
	if raycast then
		print(raycast.Instance.Name)
		
		local hitCharacter = raycast.Instance.Parent
		local hitName = raycast.Instance.Name
		local humanoid = hitCharacter:FindFirstChild("Humanoid")
		
		if humanoid then
			if hitCharacter.Name ~= player.Character.Name then
				if hitName == ("Head") then
					humanoid.Health -= headshotDamage
				else
					humanoid.Health -= damage
				end
			end
		end
	end
end)

The script is stored in ServerScriptServer

Any help is Appreciated!

4 Likes

It’s most likely because you are using debris:AddItem 0.1 seconds after it is created. I suggest increasing the time or removing said line of code to see the raycast.

2 Likes
local direction = (endPosition - startPosition).Unit * maxRange
	
local raycast = game.Workspace:Raycast(startPosition, direction)

createVisual(startPositon, direction)

Did you forgot to add “createVisual” function while on server event (which fired by mouse)? If so, I just already wrote it.

2 Likes

And yeah, also use RaycastParams. So you don’t need to wrote the statement that detects the character was you or not.

2 Likes