I’ve been trying to make a raycast shooting turret, and managed to end up with a for loop searching for current players, but when I’m trying to get the root part of the player, and calculate the magnitude, the output prints me this:
Attempted to index nil with position on line 11.
Here’s the for loop:
for i,v in pairs(game.Workspace:GetChildren()) do
local humanoid = v:FindFirstChild("Humanoid")
local root = v:FindFirstChild("HumanoidRootPart")
if (root.Position - barrel.Position).Magnitude <= 300 and humanoid.Health >= 0 then
local bulletRay = Ray.new(barrel.Position, (root.Position - barrel.Position).Unit * 500)
local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(bulletRay, {barrel})
target = root
end
end
And here is the entire code if you are interested:
local maxDist = 300
local part = game:GetService("ReplicatedStorage"):WaitForChild("Part")
local barrel = script.Parent
local playerTable = {}
while task.wait(0.5) do
local target = nil
for i,v in pairs(game.Workspace:GetChildren()) do
local humanoid = v:FindFirstChild("Humanoid")
local root = v:FindFirstChild("HumanoidRootPart")
if (root.Position - barrel.Position).Magnitude <= 300 and humanoid.Health >= 0 then
local bulletRay = Ray.new(barrel.Position, (root.Position - barrel.Position).Unit * 500)
local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(bulletRay, {barrel})
target = root
end
end
if target then
barrel.CFrame = CFrame.new(barrel.Position, target.Position)
local bullet = part:Clone()
bullet.Velocity = barrel.CFrame.LookVector
playerTable[target.Parent.Name] = target.Parent:FindFirstChild("Humanoid")
end
end
for i, v in pairs(playerTable) do
v:TakeDamage(25)
end
:FindFirstChild() returns nil when it doesn’t find the thing you are searching for, and you are searching the workspace for HumanoidRootPart meaning it will sometimes not find it. Instead if you are looking only for players you should loop through the game.Players:GetChildren() and get root by doing v.Character:FindFirstChild("HumanoidRootPart") and just in case you can put if not root then continue end after you declare the root.
Well you can not simply use game.Players:GetChildren() because the children of the players in the players path is just StarterPlayerScripts and this kind of stuff. But what I’m actually trying to do is the shooting raycast script shoot a rig inside the workspace, that’s why I was using the workspace in the for loop.
And if you are asking yeah I used your method but this time it says:
When you get a player from game.Players.Character gives you their character in the workspace, which is the best way to get someones character. For the humanoid you also have to do same thing local humanoid = v.Character:FindFirstChild("Humanoid").