Why is it doubling every time?

I made this thing where if the player clicks mouse button1, it spawns a part at the mouse location, it should only be spawning 1 part though, I cant work out why its doubling the amount of parts on every click.

Here is my code:

Client (local script in tool): ↓

wait(1)

local RS = game:GetService("ReplicatedStorage")

local Server = RS:WaitForChild("Server")

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local UIS = game:GetService("UserInputService")
local Tool = script.Parent

local Character = Player.Character or Player.CharacterAdded:Wait()
local Root = Character.HumanoidRootPart

Tool.Activated:Connect(function()
	Mouse.Button1Down:Connect(function()	

		Server:FireServer(Mouse.Hit.Position)	
		print("sent to server")

	end)
end)

Server code: (in tool) ↓


wait(1)

local RS = game:GetService("ReplicatedStorage")

local Server = RS:WaitForChild("Server")
local Replicate = RS:WaitForChild("Replicate")


Server.OnServerEvent:Connect(function(playerWhoFired, mouse)
	print("got server")

	Replicate:FireAllClients(playerWhoFired, mouse)
	print("sent to bullet replication ")

end)

Local script in StarterPlayerScripts: ↓


wait(1)

local RS = game:GetService("ReplicatedStorage")

local Replicate = RS:WaitForChild("Replicate")

Replicate.OnClientEvent:Connect(function(playerWhoFired, mouse)
	print("got replication")
	
	
	local projectile = Instance.new("Part")
	projectile.Parent = workspace
	projectile.Position = mouse
	

end)

Any help is appreciated!

Tool.Activated runs when MouseButton1 is down and you have another connection inside activated as well.

1 Like

Also, the connections in the activated connection are not being disconnected meaning everytime you click you gain another connection listening for your click.

How do I disconnect a tool being activated?

Well, you don’t really need the connection in the Activated one in the first place since the Activated one already listens for MouseButton1Click.

So basically, turn this

Tool.Activated:Connect(function()
	Mouse.Button1Down:Connect(function()	

		Server:FireServer(Mouse.Hit.Position)	
		print("sent to server")

	end)
end)

into this

Tool.Activated:Connect(function()
	Server:FireServer(Mouse.Hit.Position)	
	print("sent to server")
end)
1 Like

I did that yes that fixed it, I also have another problem though, for some reason when there are 2 players in the server it will spawn in 2 parts per click and if there are 3 players it will spawn 3 parts and so on, why is this?

This is because every player has a tool, with a server script listening to the Replicate remote. You should instead have the script in ServerScriptService so it is centralized.

1 Like

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