Why is this script not working?

Basically i’m trying to make a gun that only damages the npcs, problem is it damages players too!

local re = script.Parent:WaitForChild("RemoteEvent")
local damage = 10
local bang = script.Parent.pistol.GunShot

re.OnServerEvent:Connect(function(player, target)
	bang:Play()
	if target then
		local model = target.Parent
		if model:FindFirstChild("Humanoid") then
			for i, v in pairs(game:GetService("Players"):GetPlayers()) do
				if model:FindFirstChild("Humanoid") then
					if model.Name ~= v.Name then
						print(model)
						local hum = model:FindFirstChild("Humanoid")
						hum:TakeDamage(damage)
					end
				end
			end
		end
	end
end)
1 Like

I replaced the for loop with an if statement.

See if this works.


Script

local Players = game:GetService("Players")--Get the "Players" Service
local re = script.Parent:WaitForChild("RemoteEvent")
local damage = 10
local bang = script.Parent.pistol.GunShot

re.OnServerEvent:Connect(function(player, target)
	bang:Play()
	if target then
		local model = target.Parent
		if model:FindFirstChild("Humanoid") then
			if Players:GetPlayerFromCharacter(model) then return end --if it's not a player then continue
			
			print(model)
			local hum = model:FindFirstChild("Humanoid")
			hum:TakeDamage(damage)
		end
	end
end)
2 Likes

I am not entirely sure how your calling these remotes or what arguments you are sending so I have no idea how to fix your exact issue

Please support how you’re calling the Event
Ex…: RemoteEvent:FireServer(Target)
Is target a player?? a model??

target. its the mouse targetr lmao

So if I am correct it returns a model?

1 Like
local re = script.Parent:WaitForChild("RemoteEvent")
local damage = 10
local bang = script.Parent.pistol.GunShot
local Players = game:GetService("Players")

re.OnServerEvent:Connect(function(player, target)
	bang:Play()
	if (target) then
		local Character = Players:GetPlayerFromCharacter(target) or Players:GetPlayerFromCharacter(target.Parent)
		if (Character) then
			local hum = Character:FindFirstChild("Humanoid")
			hum:TakeDamage(damage)
		end
	end
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.