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

How do I make a damage script that does not hit the player twice?

Hi I'm trying to make a grenade tool and I'm working on the damage this is what I got

hitplayers = {}


script.Parent.Touched:Connect(function(hit)
	local obj = hit.Parent
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hit.Parent.Name == "Outrider" and hit.Parent ~= script.Wielder.Value and hit.Parent ~= hitplayers then
		table.insert(hitplayers,hit.Parent)
		hum:TakeDamage(50)
	end
end)

I'm trying to make it so it wont hit the same player twice how do I fix this?

2 answers

✓ Accepted answer

You're attempting to compare an object with an array! You would have to iterate through hitplayers and compare each index.. but rather than inserting the object as the value, insert it as the key for ease of access! I'll show you:

local hitplayers = {};

script.Parent.Touched:Connect(function(hit)
	local obj = hit.Parent
	local hum = hit.Parent:FindFirstChild("Humanoid")
	--separated conditions so it looks cleaner
	local outrider = hit.Parent.Name == "Outrider";
	local noWield = hit.Parent ~= script.Wielder.Value;
	local alreadyHit = hitplayers[obj]; --ease of access
	if outrider and noWield and not alreadyHit then
		hitplayers[obj] = true; --set as key
		hum:TakeDamage(50)
	end
end)
local DamagedPlayers = {}

function checkDamagedPlayers(PlayerName)
	for i,v in pairs(DamagedPlayers) do
		if v == PlayerName then
			return true
		end
	end

	return false
end

function onTouched(Part)
	local Character = Part:FindFirstAncestorWhichIsA("Model")
	

	if Character and Character.Humanoid then
		local inDamagedPlayers = checkDamagedPlayers(Character.Name)

		if Character.Name == "Outrider" and Character ~= script.Wielder.Value and inDamagedPlayers ~= true then
			table.insert(DamagedPlayers,Character)
			Character.Humanoid:TakeDamage(50)
		end
	end
end 

script.Parent.Touched(onTouched)

We have declare a table called "DamagedPlayers", and a function that checks if a specific item is within the table. The damage code is the same except we use the function checkDamagedPlayers.

10 comments

0

now it does not do damage at all

0

oh you forgot to connect the function maybe

0

it kills him all the way its suppose to take half health but thanks

0

OH YEAH I FORGOT TO CONNECT THE FUNCTION MY BAD

0

wait i connected the touch function what about the other one?

0

its not supposed to be connected

0

ok it still does not work

0

You're inserting the character instance into the array, and checking their name.. :P

0

You're inserting the character instance into the array, yet checking the name in the function.. :P

0

yeah I made that mistake a lot yesterday

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