How to stop script from running too much times

  1. What do you want to achieve?

i want to make give exp to the player when the NPC dies.

  1. What is the issue?

When I kill an NPC, it does give me an exp, but it gives too much.
npc gain 100 exp
image

  1. What solutions have you tried so far?
									if enemy:FindFirstChild("ExpGain") then
										Player.Stats.Exp.Value = Player.Stats.Exp.Value + enemy:FindFirstChild("IsAnNpc").Value
									end
								end)

You can use a debounce to stop the code from running multiple times:

local players = game:GetService("Players")

local player = players.LocalPlayer

local enemy = -- Path to your enemy

local debounce = false

local cooldown = 1

enemy.Humanoid.Died:Connect(function()
    if enemy:FindFirstChild("ExpGain") then
       if debounce == false then
          debounce = true

          player.Stats.Exp.Value += enemy:FindFirstChild("IsAnNpc").Value

          task.wait(cooldown)

          debounce = false
       end
    end
end)

Learning Requirements:

1 Like