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

-50 health when touching a part script. How do I only take away 50 health?

Asked by 5 years ago

When I use this script it makes my character health go down insanely fast. I don't want that. I only want it to go to 50 health.

Here is my script

script.Parent.Touched:Connect(function(hit)
    local char  = hit.Parent:FindFirstChild("Humanoid")
    char.Health = char.Health - 50
end)

1 answer

Log in to vote
0
Answered by
RAYAN1565 691 Moderation Voter
5 years ago

When using a debounce, you must satisfy all four parts:

  1. Index a variable and set it to false (or true if you want but we'll focus on the former).

  2. Within the if-then statement, check for whether the variable is set to false. If it is, the code will continue to run. If not, the code will not execute further.

  3. Usually the next line after the if-then statement, change the variable to the opposite (in this case, we'll change it to true). This prevents the script to run the code again since the variable is no longer equal to false. Thus the if-then statement fails and the rest of the code will not run which is what we want. We want the code to run once and not multiple times.

  4. After the code has executed completely, we change the variable back to false.

In your script, we will implement this:

local debounce = false

script.Parent.Touched:Connect(function(hit)
    if debounce == false then
        debounce = true
        local char  = hit.Parent:FindFirstChild("Humanoid")
        char.Health = char.Health - 50
    end
    debounce = false
end)

But, we're not finished yet. This still fails. We're going to implement a second debounce to ensure this only runs once and not multiple times:

local debounce = false
local i = 0

script.Parent.Touched:Connect(function(hit)
    if debounce == false and i == 0 then
        debounce = true
        i = i + 1
        local char  = hit.Parent:FindFirstChild("Humanoid")
        char.Health = char.Health - 50
    end
    debounce = false
    i = 0
end)
0
You can do 'if debounce then' (or 'if not debounce then') which will make it a bit easier and shorter to write than 'if debounce == false' User#20388 0 — 5y
Ad

Answer this question