Raycast problem

I wrote a script just to test the raycast, but sometimes it gives an error and sometimes it works. I’ve tried several things but none of them solved my problem. I have a script that creates the green neon block and using weld it stays on the character, and this block is the origin of the raycast and the direction is the position of my mouse, and where the raycast goes, it creates this purple block, but sometimes it works and sometimes it gives this error. I will be leaving the code for the raycast and the weld below.

Script:12: attempt to index nil with ‘Instance’

Raycast:

script.Parent.OnServerEvent:Connect(function(Player, Mouse)
	local Head = Player.Character.Head
	local StartPos = workspace:FindFirstChild("RAIO").Position
	local EndPos = Mouse.Position

	local Params = RaycastParams.new()
	Params.FilterType = Enum.RaycastFilterType.Exclude
	Params.FilterDescendantsInstances = {Player.Character}

	local ray = workspace:Raycast(StartPos, EndPos - StartPos, Params)

	if ray.Instance then
		local Block = Instance.new("Part", workspace)
		Block.Size = Vector3.new(4, 4, 4)
		Block.Color = Color3.new(0.933333, 0, 1)
		Block.Anchored = true
		Block.Position = ray.Position
		Block.Transparency = 0.4
		Block.CanCollide = false
	end
end)

Weld:

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function(Character)
		local Attachment = Instance.new("Part", workspace)
		Attachment.CFrame = Character.Head.CFrame * CFrame.new(0, 0, -4)
		Attachment.Name = "RAIO"
		Attachment.Size = Vector3.new(0.4, 0.4, 0.4)
		Attachment.Anchored = false
		Attachment.Color = Color3.new(0.333333, 1, 0)
		Attachment.Material = Enum.Material.Neon
		Attachment.CanCollide = false
		
		local Weld = Instance.new("WeldConstraint", Character.Head)
		Weld.Part0 = Character.Head
		Weld.Part1 = Attachment
	end)
end)```

Try replacing

if ray.Instance then

with

if ray and ray.Instance then
1 Like

I no longer have the error in the output with your solution, however, it fails a lot. Like, I keep pressing E so that the Remote is fired, but it doesn’t always create the purple block on the wall, I have to keep pressing and sometimes it works and sometimes it doesn’t. How do I fix this so that it always works?

local ray = workspace:Raycast(StartPos, (EndPos - StartPos)*1.1, Params)

Now does it work?

1 Like

Wow, now it works 100%! Could you explain why it works with this multiplication? I really want to understand this if possible. Thank you a lot man!

The raycast’s position is located EXACTLY on the wall, so your shooting the ray with the length of (EndPos - StartPos).Magnitude, which is only enough to reach the wall, so there’s only 50% chance of the ray touching. This quite similar to z fighting imo

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.