Search code examples
luaroblox

:GetChildren() not working for an unknown reason


so, i'm trying to make a baldi's basics type game

(here's my code for the hearing script)

local baldi = script.Parent
local neededConfig = require(game.ReplicatedStorage.modules.configs.tags)
local targ = baldi.Target
local crime = targ.Crime
local minDistance = 200

function getHRP(c:Model)
    local t = c:GetChildren()

    for _, part in pairs(t) do
        if part:IsA("BasePart") then
            if part.Name == "HumanoidRootPart" then
                return part
            end
        end
    end

    return nil
end

function speedup(boostTime, briefSpeedup)
    baldi.Speed.Value += briefSpeedup

    task.delay(boostTime, function()
        baldi.Speed.Value -= briefSpeedup
    end)
end

function listen()
    local nearest = minDistance

    crime.Value = "baldi"

    for _, p in pairs(game.Players:GetPlayers()) do
        local c = game.Players:FindFirstChild(p.Name, true).Character

        if getHRP(c) ~= nil then
            local hrp = getHRP(c)
            local dist = (hrp.Position - baldi.HumanoidRootPart.Position).magnitude

            if dist <= nearest and c:HasTag(neededConfig.tags.sound) then
                nearest = dist
                targ.Value = p

                if baldi.Wandering.Value ~= 0 then
                    speedup(15, 1.25)
                    baldi.Wandering.Value = 0

                    task.delay(30, function()
                        baldi.Wandering.Value = 1
                    end)
                end
            end
        end
    end
end

spawn(function()
    repeat
        task.wait()
        listen()
    until baldi == nil
end)

on line 8 when i call GetChildren, it errors saying attempted to index nil with GetChildren and i cant figure out why

i havent seen any solutions yet, so i'm just kind of confused as to why my code is failing


Solution

  • As @AKX pointed out, the error is telling you that for some reason c is nil. So you need to look where you call getHRP...

        for _, p in pairs(game.Players:GetPlayers()) do
            local c = game.Players:FindFirstChild(p.Name, true).Character
    
            if getHRP(c) ~= nil then
    

    When a player joins the game or has just died, there is a brief time where their Character model doesn't exist. So player.Character will be nil until their character respawns in the world.

    So you need to add safety checks so you aren't trying to access an object that doesn't exist :

        for _, player in pairs(game.Players:GetPlayers()) do
            local c = player.Character
            if c and getHRP(c) ~= nil then