Raycast has a chance of returning nil

https://streamable.com/0n16fx

Local Script:

--//Services
local Run_Service = game:GetService("RunService")
local User_Input_Service = game:GetService("UserInputService")
local Player_Service = game:GetService("Players")

--//Tool
local Tool = script.Parent

--//Player
local Player = Player_Service.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local Mouse = Player:GetMouse()

--//Events
local Weapon_Remote = script.Weapon_Remote

--//Attributes
local Cooldown_Time = 2

--//Values
local Cooldown = false

--//Tables

--| Main Script |--
local function Activated()
	if Cooldown == false then
		Cooldown = true
		
		local Start_Position = Tool.ShootPos.Position
		local End_Position = Mouse.Hit.Position
		
		Weapon_Remote:FireServer(Start_Position, End_Position)
		task.wait(Cooldown_Time)
		Cooldown = false
	end
end

Tool.Activated:Connect(Activated)

server:

--//Services
local Run_Service = game:GetService("RunService")
local User_Input_Service = game:GetService("UserInputService")
local Player_Service = game:GetService("Players")

--//Tool
local Tool = script.Parent.Parent

--//Events
local Weapon_Remote = script.Parent.Weapon_Remote

--//Attributes
local Range = 200
local Damage = 50

--//Tables
local Body_Parts_Hit = {}

local function Shoot(Player, Start_Position, End_Position)
	print("Shooting")
		local Direction = End_Position - Start_Position

		local RayCast_Params = RaycastParams.new()
		RayCast_Params.FilterDescendantsInstances = {Tool, Player.Character or Player.CharacterAdded:Wait()}
		RayCast_Params.FilterType = Enum.RaycastFilterType.Exclude
		local RayCast_Result = workspace:Raycast(Start_Position, Direction, RayCast_Params)

		if RayCast_Result then
		if RayCast_Result.Instance.Parent:FindFirstChild("Humanoid") then
			
				local Target = RayCast_Result.Instance.Parent
				local Body_Part = RayCast_Result.Instance
				
				print(RayCast_Result.Instance.Name)
				table.insert(Body_Parts_Hit, Body_Part)
				if Body_Parts_Hit == {"Head"} then
					Target.Humanoid:TakeDamage(Damage * 3)
				else
					Target.Humanoid:TakeDamage(Damage)
				end
			else
				print("Given Instance was not a humanoid, Instance is a: "..RayCast_Result.Instance.Name)
		end
		local Part = Instance.new("Part", workspace)
		local hightLight = Instance.new("Highlight", Part)
		Part.Size = Vector3.new(1,1,1)
		Part.Position = RayCast_Result.Position
		Part.Anchored = true
	else
		print("Raycast Object Returned as nil")
	end
	end

Weapon_Remote.OnServerEvent:Connect(Shoot)
1 Like

The raycast returns nil when it encounters nothing in its path, you can either increase the distance it travels, or check if the part it encounters have CanQuery enabled