Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there any better ways for GetchildenScript? Thanks for help!

Asked by 5 years ago

This is my codes:

local Ghosts = workspace.Ghosts:GetChildren() -- this is a folder.

for i=1,#Ghosts - 1 do
    local Ghost
    local Distance = Player:DistanceFromCharacter(Ghosts[i].PrimaryPart.Position)
    local NextDistance = Player:DistanceFromCharacter(Ghosts[i+1].PrimaryPart.Position)
    if Distance < NextDistance then
        Ghost = Ghosts[i] 
    else
        Ghost = Ghosts[i+1]
    end
end

My code only can get two ghosts :C
Does there the better way to change this?
I want make it can get two or up.
Thanks for answering!

1 answer

Log in to vote
1
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago

If you want to get the closest ghost to the character, you can do something like this:

local Ghosts = workspace.Ghosts:GetChildren()

local function GetClosestGhost(Player)
    if Player.Character and Player.Character:FindFirstChild("HumanoidRootPart") then

        local ClosestDist = math.huge
        local ClosestGhost
        for _,Ghost in pairs(Ghosts) do
            local GhostDistance = (Ghost.PrimaryPart.Position - Player.Character.HumanoidRootPart.Position).magnitude
            if GhostDistance < ClosestDist then
                ClosestDist = GhostDistance
                ClosestGhost = Ghost
            end
        end
        print("The closest ghost is", ClosestGhost)
        return ClosestGhost
    end
end

local Ghost = GetClosestGhost(PlayerHere)

This will iterate through every ghost while keeping track of the last closest ghost and the last closest distance. If a ghost is closer than the last closest distance, it will update the closest ghost to be the new one. Then, by the end, whichever ghost was the closest is returned.

Ad

Answer this question