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

How do I set up a function that waits for an event to fire but also returns a bool if it times out?

Asked by 5 years ago

Say I wanted to add a "shield" to be depleted before health when a player takes damage, and said shield would regenerate on its own if no damage is taken in 10 seconds. How could I setup a function that waits a certain duration and returns true if the duration expires?

I read somewhere about using :wait() in this way but I have no idea how to have it return values.

function waitForChange(element, duration)
    repeat until element.Changed:wait(duration) --Return false if event fires before duration
    -- Return true if nothing fires
end

Sorry if the answer is actually really obvious, I'm very much a beginner at this.

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

What you could do is create a timer that counts down from 10 and is refreshed every time damage is taken, which would have to be tracked by a separate function.

I'll assume you're using a humanoid for this.

function waitforchange(shield, duration, humanoid)
    currentHealth = humanoid.Health
    local healthchangedevent = humanoid.HealthChanged:connect(function(health)
        if health < currentHealth then
            print("Shield damaged. Regeneration timer reset.")
            duration = 10
        end
        currentHealth = health
    end)
    while shield do
        while duration > 0 do
            wait(1)
            duration = duration - 1
            print(duration.." seconds until shield regenerates.")
        end
        repeat humanoid.Health = humanoid.Health+5 wait(.1) until humanoid.Health == humanoid.MaxHealth or duration > 0
    end
    print("Shield destroyed!")
    shield:Destroy()
    healthchangedevent:Disconnect()
end

This script was not actually tested so if you find any flaws please message me. And no, the answer was not really obvious.

0
just realized I wrote this incorrectly but this should work for you anyways steven73598233 75 — 5y
0
I can kind of see where you're going with that. I probably should've given you more info on how I'm handling shield (that's my bad) but I can use your script as a guideline. Thanks a bunch! Perthrosama 24 — 5y
Ad

Answer this question