Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Loops and Values?

What I'm trying to do is when a humanoid's health is above 50, it will try to get to 100 by adding 1 every 2 seconds.

while wait() do
	script.Parent.Value = script.Parent.Parent.Parent.Humanoid.Health
end
script.Health.Changed:connect(function() --The value is inside the script
	if script.Parent.Humanoid.Health >= 50 then
		for i = script.Parent.Humanoid.Health, 100, 1 do
			script.Parent.Humanoid.Health = script.Parent.Humanoid.Health + i
			wait(2)
		end
	end
end)

1 answer

✓ Accepted answer

Cleaning up code

Before we get into a solution, I'd like to suggest a better way to record the humanoid's health. In this example, I'll be using the HealthChanged event, and a variable to store the number rather than a Value object (though if you need that Value object for a specific purpose, it'll be pretty easy to implement).


I'll also be creating more references to objects we'll be using multiple times, so we don't have to continuously access it through it's hierarchy. Here's an example:

-- Get the local player
local Player = game:GetService("Players").LocalPlayer

-- Get, or wait for the character.
local Character = Player.Character or Player.CharacterAdded:wait()

-- When the character has been returned, wait for it's Humanoid.
local Human = Character:WaitForChild("Humanoid")

-- Create the variable for the character's health outside the event
local CharHealth

-- The event fired when the health changes
Human.HealthChanged:connect(function(health)

	-- Set the health outside the event
	CharHealth = health 

-- End the event
end)

-- Loop that checks the health every 2 seconds
while wait(2) do

	-- If the CharHealth is above 50, then...
	if CharHealth > 50 then

		-- Increment the Humanoid's health value by 1
		Human.Health = Human.Health + 1

	-- End if statement
	end

-- End loop
end

Hope this helped. Let me know if you have any questions.

This discussion is preserved as it was. New answers, comments, and votes are closed.