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

Tool giver doesn't work on the second click?

A script in the ServerScriptService:

local rs = game.ReplicatedStorage
local gun = rs:WaitForChild("M1911"):Clone()
local model = rs:WaitForChild("M1911Giver"):Clone()
tool = game.Workspace:WaitForChild("M1911Giver")
click = tool:WaitForChild("ClickDetector")

local function onMouseClick(plr)
	gun.Parent = plr.Backpack
	tool:Destroy()
	wait(10)
	model.Parent = game.Workspace
	model.Position = game.Workspace.M1911Spawn.Position
end
  
click.MouseClick:connect(onMouseClick)

What my script does is when a part is clicked, it will give the player a tool. It then waits 10 seconds and you can click it again for another tool. But when I click it a second time it doesn't work and there are no errors.

1 answer

✓ Accepted answer

So what's going on here is that you are deleting the giver (line 09) and that is resetting the event connection on line 15.

click.MouseClick:connect(onMouseClick)

click comes from tool and you do tool:Destroy(). It seems you replace this giver with model but the ClickDetector in that model is never re-connected to. We can fix this by re-adding the connection in your script. There's actually another problem with this script. You only make one clone of model and gun.

local gun = rs:WaitForChild("M1911"):Clone()
local model = rs:WaitForChild("M1911Giver"):Clone()

That means this script won't work when the giver is used for the second time (it runs out of clones to give). We can fix this in the end by doing the cloning in the function instead. That way it is cloned each time.

local rs = game.ReplicatedStorage
local gun = rs:WaitForChild("M1911")
local model = rs:WaitForChild("M1911Giver")
tool = game.Workspace:WaitForChild("M1911Giver")
click = tool:WaitForChild("ClickDetector")

local function onMouseClick(plr)
    local gunClone = gun:Clone()
    gunClone.Parent = plr.Backpack
    tool:Destroy()
    wait(10)
    tool = model:Clone()
    tool.Parent = game.Workspace
    tool.Position = game.Workspace.M1911Spawn.Position
    click = tool:WaitForChild("ClickDetector")
    click.MouseClick:connect(onMouseClick)
end

click.MouseClick:connect(onMouseClick)

I am not too sure about connecting to a function within itself. I don't think that makes a huge stack because event connections aren't blocking ...

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