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

Script won't stop adding trees - how to stop?

So this code is a plugin, which adds trees at the mouse's location. When I click to stop, it does not work. Here is the code:

-- Create a new toolbar section titled "Custom Script Tools"
open =  false
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local toolbar = plugin:CreateToolbar("Custom Script Tools")
local ChangeHistoryService = game:GetService("ChangeHistoryService")

 
-- Add a toolbar button named "Create Empty Script"
local newScriptButton = toolbar:CreateButton("Create Snow Tree", "Create a Snow Tree", "rbxassetid://4458901886")

local function onNewScriptButtonClicked()
	if open == false then
		open = true
		print("Awesomemode14 Plugin is Open")
		local folder = Instance.new("Folder")
		folder.Parent = game:GetService("Workspace")
		folder.Name = "Snow Trees"
		mouse.Button1Down:Connect(function()
			local tree = game.ReplicatedStorage:WaitForChild("SnowTree")
			local treeClone = tree:Clone()
			treeClone.Parent = folder--game:GetService("Workspace")
			treeClone:SetPrimaryPartCFrame(CFrame.new(mouse.Hit.X, 15.855, mouse.Hit.Z))
			ChangeHistoryService:SetWaypoint("Added new tree")			
		end)		
	else 
		open = false
		mouse.Button1Up:Connect(function()end)
		print("Awesomemode14 Plugin was Closed")			
	end	
end
newScriptButton.Click:Connect(onNewScriptButtonClicked)

Thanks for the Help!

1 comment

0

I do believe there is no "player" object in studio. And if I'm not mistaken(which I might be) you can just use plugin:GetMouse(),

1 answer

✓ Accepted answer

For this problem you should familiarize yourself with Events, like for instance the Button1Down mouse Event which fires a signal every time the mouse button is pressed down.

Your current issue is that you are binding the mouse click to your function Button1Down:Connect(function() but then have no way to disconnect this event afterwards. What's worse, you try to bind a new function to this event, creating an ever increasing memory leak.

What you should do, is store the event you are binding as a variable - which can be done like so:

local treeEvent = mouse.Button1Down:Connect(function()
	--stuff
end)

This is possible because the :Connect function returns the event it creates!

So now that we have the event stored in a variable, we can call the :Disconnect() function whenever we want to stop the game from listening for your mouse click.

This means replacing:

mouse.Button1Up:Connect(function()end)

With:

treeEvent:Disconnect()

Hope this helps!

2 comments

0

How would I call the variable?

0

I'm not sure what you mean by call the variable. It's just a reference to the event you created. If you mean rebinding the event, you have to use :Connect() again.

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