Help on how to get the highest value of a number value inside multiple objects that are inside a folder

Hey! u may already have seen me around here and know that im making a tower defense game

And after doing the lobby music im working on a better tower system, and im making it so the player can select if it will attack the closest enemy or the strongest enemy, etc

And im stuck at the part of getting the zombie that has the highest help

Btw how this system works is, theres a folder named Zombies that has all the zombies which are in the map, instead of using a humanoid for the health i used a number value so they dont die they just disappear, making it more clean

Could anyone help me?

local Zombies = script.Zombies --path to folder 

local result
local biggest_health = 0
for _, zombie in pairs(Zombies:GetChildren()) do 
	local Health = zombie:FindFirstChild("Health") --where Health is the name of NumberValue 
	if not Health then continue end 
	local val = Health.Value
	if not result or val > biggest_health then 
		biggest_health = val 
		result = zombie 
	end
end

print(result) --chosen zombie
local highestHealthZombie
local highestHealth

for _, zombie in pairs(zombies) do
    local health = zombie:FindFirstChild("Health") -- or whatever it's called
    if health then
        if highestHealth then
            if health > highestHealth then
                highestHealth = health
                highestHealthZombie = zombie
            end
        else
            highestHealth = health
            highestHealthZombie = zombie
        end
    end
end

Thx! But could u explain to me what it does?

Thx! This also helped!

character69420

Basically, it loops through each zombie and checks the health of it. If the health is higher than the previous highestHealth, then highestHealth will be set to the new health. If it’s less than the current health, then it will ignore it and move on.

And also makes an exclusion, if the zombie is the first one being checked.

Ohhh thx! ima implement this into the system, it will probably work!

Oh but does the script already makes the exclusion or i need to implement thst into it

Both of the scripts make the exclusion, just in a different way.

1 Like