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

How to not add another value if there is already an existing one?

So, I am basically trying to make it so when you hit an NPC it adds an object value to it but when I hit it adds like 20 or more so if anyone knows how to fix it so it only adds one value to the NPC.

Here is the script:

(it's a server script by the way).

local tool = script.Parent.Parent

local Debris = game:GetService("Debris")
local Players = game:GetService("Players")

tool.Equipped:Connect(function()
character = tool.Parent
player = game.Players:GetPlayerFromCharacter(character)
end)

local function TagHumanoid(humanoid) -- Function to add the object value
local CreatorTag = Instance.new("ObjectValue")
CreatorTag.Parent = humanoid
CreatorTag.Value = player
CreatorTag.Name = "creator"
Debris:AddItem(CreatorTag, 1)
end

local function UnTagHumanoid(humanoid) -- Function to delete the object value
for i, v in pairs(humanoid:GetChildren()) do
if v.Name == "creator" and v:IsA("ObjectValue") then
wait(0.5)
v:Destroy() end
end
end

script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local Humanoid = hit.Parent:FindFirstChild("Humanoid")
TagHumanoid(Humanoid)
UnTagHumanoid(Humanoid)
end)

1 answer

✓ Accepted answer

Try adding a debounce. If you don't know how debounces work here's a simple demonstration.

local debounce = false

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") and debounce == false then
		debounce = true
		
		local Humanoid = hit.Parent:FindFirstChild("Humanoid")
		TagHumanoid(Humanoid)
		UnTagHumanoid(Humanoid)

		wait(4) -- Waits 4 seconds until this code block can be run again. (basically a cooldown)
		debounce = false -- Debounce gets set to false so that the code block can be run agian.
	end
end)

1 comment

0

Thanks it worked

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