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)```