i have a script:

local SearchDistance = 10000

local NPC = script.Parent
local HRP = NPC.HumanoidRootPart
local Humanoid = NPC:FindFirstChildOfClass("Humanoid")

local function getNearestPlayer()
    local playerDistances = {}
    if HRP then 
        for i, player in pairs(game.Players:GetPlayers()) do 
            -- get the distance between the player's character and the HRP's position
            local distance = player:DistanceFromCharacter(HRP.Position)
            -- 'table.insert(x, y, z)' has 3 arguments. x = table(array), y = number position (optional), z = variable/object/instance your adding to the table
            table.insert(
                playerDistances,
                {
                    player,
                    distance
                }
            )
        end
    end
    if #playerDistances >= 1 then 
        --'table.sort(x, y)' has 2 arguments. x = table(array), y = function (optional)
        table.sort(
            playerDistances,
            function(a, b) -- 'a' and 'b' is the data/table inserted into the 'playerDistances' table
                -- we are comparing the distances and ordering them from least to greatest
                -- so we get the data's second value 'a[2]' and 'b[2]' which is the distances
                return a[2] < b[2]
            end
        )
        for i, dataTable in pairs(playerDistances) do  
            local player = dataTable[1]
            local distance = dataTable[2]
            if player and distance then 
                -- 'i' is the number position of the 'dataTable'
                if i == 1 and distance < SearchDistance then 
                    return player
                end
            end
        end
    end
end

while HRP and Humanoid.Health > 0 do 
    wait(.5)
    local nearestPlayer = getNearestPlayer()
    if nearestPlayer and nearestPlayer.Character.Masked.Value == true then 
print("detected")
script.Parent.Torso.Anchored = false
script:Destroy()
    end
end

and it goes only up to print thing and not the torso.anchored thing, it prints detected but says parent is nil, so i changes script to this:

wait(.5)
script.Parent.Torso.Anchored = false

then it changed torso to unanchored, why?

1 comment

0

might wanna add a delay before you destroy the script.