Help with an snowball projectile hitbox

Hi I need help with my code. My if statement isn’t working and I’m confused. I do not get any errors but my snowball doesn’t get destroyed! Note: If I remove the not in the non working if statement, it does the opposite of what the code is supposed to do

script.Parent.Touched:Connect(function(hit) -- Checks if the snowball has been touched
	local hitName = hit.Parent.Name -- Stores the thing that hit it parent's name	
	local h = hit.Parent:FindFirstChild("Humanoid") -- Selecting humanoid
	if hit.Parent.ClassName == "Accessory" then -- Checks if the parent is a Accessory to make sure it has hit a player
		hitName = hit.Parent.Parent.Name
		h = hit.Parent.Parent:FindFirstChild("Humanoid")
	end
	print(script.Parent:GetAttribute("PlayerName").. hitName) -- Gets info that goes into the if statement
	if not script.Parent:GetAttribute("PlayerName") == hitName then -- Not firing
		if h then -- Checks if the object hit has an Humanoid
			h.Health = h.health - 20 -- Deals damage
		end 
		script.Parent:Destroy() -- Destroys the snowball
	end
end)

It looks like the attribute is stored as "PlayerName".. hitName but you are searching for just "PlayerName"

Its in an object and that’s how it stores the name of the player that threw it (in an attribute) Also that’s a print object. It just prints what should go in.

Hopefully the PlayerName attribute is the players’s username and not their display name.

You can try this:

script.Parent.Touched:Connect(function(hit) -- Checks if the snowball has been touched
	local humanoid = hit.Parent:FindFirstChildWhichIsA("Humanoid") -- Find humanoid statement
	
	if humanoid and (script.Parent:GetAttribute("PlayerName") ~= hit.Parent.Name) then
		humanoid.Health -= 20 -- Deals damage regardless of forcefields | humanoid:TakeDamage(20) deals damage if they don't have a forcefield
	end
	script.Parent:Destroy() -- Destroys the snowball
end)
1 Like

Weird. It just destroys the snowball from the point it gets thrown

Fixed it! I had to remove the not and change the == to ~=! Thanks for your help though!

“not” would’ve worked you just needed to wrap the following expression inside a pair of parentheses so that it’s evaluated first before the not statement is applied.

I’ve made a few slight improvements.

script.Parent.Touched:Connect(function(hit)
	local hitName
	local h
	if hit.Parent:FindFirstChild("Humanoid") then
		hitName = hit.Parent.Name
		h = hit.Parent:FindFirstChild("Humanoid")
	elseif hit.Parent:IsA("Accessory") then
		hitName = hit.Parent.Parent.Name
		h = hit.Parent.Parent:FindFirstChild("Humanoid")
	end
	
	if hitName and h then
		print(script.Parent:GetAttribute("PlayerName")..hitName)
		if script.Parent:GetAttribute("PlayerName") ~= hitName then
			h.Health -= 20
			script.Parent:Destroy()
		end
	end
end)