I want to make an area in which you lose health, but once out, you don't.
So i have created a part, made transparency to 1
, and canCollide to false
, than put it inside of water. In the code character loses health when enter water, but still lose when out.
This is a code i have
local parent = script.Parent -- the part
local Player = game:GetService('Players')
local isInWater = false
local setHealth = 0
local function onCollide (hit)
local character = hit.Parent
local player = Player:GetPlayerFromCharacter(character)
local humanoid = character:FindFirstChild('Humanoid')
isInWater = true
print('in water')
if player and humanoid and isInWater then
for initalHealth = humanoid.Health, setHealth, -10 do
humanoid.Health = initalHealth
task.wait(.2)
end
end
end
parent.Touched:Connect(onCollide)
parent.TouchEnded:Connect(function()
isInWater = false
print('left water')
task.wait(1)
end)
I made a variable isInWater
, which is set to false by default, but once you collide with parent
it sets to true, in for loop it's mandatory to work with isInWater
being set to true.
Then came up with yet another function for TouchEnded
event to set isInWater
to false once you end touching the part.
Now for loop should probably stop.
Than i thought that for loop
won't stop because loop have already begun the job. So what can i do? I'm new to Lua, so any help would be appreciated
Your onCollide
function runs every time something enters the collision box of the transparent part, but the part of your code that is giving you problems is this:
isInWater = true -- this runs every time onCollide runs
What this is doing is that isInWater
is being set to true
every single time onCollide
runs, when you should really check for the player before running your for-loop.
Then, inside of your for-loop, to check if the player is still in the water, you should insert:
if not isInWater then -- breaks the for loop when not in water
break
end
before you decrement health.
Hope I helped!