I’m trying to make a guarding script that rotates you to the nearest player, however, when there is no other player with a ball to rotate to, it produces an error on every input.
local function Finder()
local balls = {}
local players = workspace.Players
for i, v in pairs(players:GetDescendants()) do
if (v:IsA("BasePart") and v.Name == "Ball") then
table.insert(balls, v)
end
end
return balls
end
local function GetBaller()
local list = Finder()
local baller = nil
local dist = 99999
local temp = nil
local human = nil
local temp2 = nil
local pos = Root.Position
for i = 1, #list do
temp2 = list[i]
temp = temp2
if (temp ~= nil) then
local mag = (temp.Position - pos).magnitude
if mag < dist then
dist = mag
baller = temp
end
end
end
return baller.Parent
end
In order to avoid nil errors, how can I call these functions and then use them in:
local baller = GetBaller()
local ballerroot = baller.HumanoidRootPart
Which I call in Input functions. Without getting millions of nil errors that baller.Parent does not exist when there is no other player
There are a few things you could do, for instance, checking if list is nil or not. This is because in your script you’re relying on list to have some sort of value. You could also implement pcalls for extra error guard if you would like. If I misunderstood anything your if you don’t understand what I’m suggesting, feel free to let me know
Read more about pcalls here (although just making sure list isn’t empty should suffice)
Also in the future make sure to provide the errors that it produces!
This won’t necessarily work because from what I see, list is returning empty/nil, which would mean it would error at for i = 1, #list do temp2 = list[i] because the script is trying to look through the returned table, which is possibly, well, nothing.
local function GetBaller()
local list = Finder()
local baller = nil
local dist = 99999
local temp = nil
local human = nil
local temp2 = nil
local pos = Root.Position
for i,v in pairs(list) do
local mag = (v.Position - pos).magnitude
if mag < dist then
dist = mag
baller = v
end
end
if baller == nil then
return nil
else
return baller.Parent
end
end
I just rewrote the whole thing (there looked to be quite a few unnecessary or unused variables)
local Root = game:GetService("Players").LocalPlayer.Character:WaitForChild("HumanoidRootPart")
local function GetClosest()
local closest = {nil, math.huge}
for i,v in pairs(game:GetService("Players"):GetPlayers()) do
if v.Character ~= nil and v.Character:FindFirstChild("Ball") then
if (Root.Position - v.Character.Ball.Position).Magnitude < closest[2] then
closest = {v, (Root.Position - v.Character.Ball.Position).Magnitude}
end
end
end
return closest[1]
end
(Depending on the location of the Ball , you may need to change the location on line 5.