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

how do i make mouse.Target remove 1 part not 5?

So i am making a building game and this code removes 5 parts instead of one and the parts that are being removed are named 'Grass' i dont really know where to go from here.


function update()
	mouse = game.Players.LocalPlayer:GetMouse()
	target = mouse.Target
	if mouse.Target ~= nil then
		if mouse.Target.Name == "Grass" then
			print'grass'
			mouse.Button1Down:connect(function()
				mouse.Target:Remove()
			end)
			
		end
	end
end

while wait() do
	update()
end

1 answer

What you are doing here is constantly waiting for the mouse to hover over grass.

Every moment that the mouse hovers on grass, you say "OKAY, START LISTENING FOR MOUSE CLICKS" (line 07). These will add up and all happen when you click (which is why you are getting many deleted at once).

It's also why you are deleting other objects, since the deleting function doesn't actually check that the target exists and is called "Grass"


That is wrong.

Instead, you wait for a mouse click, and check THEN delete that target.

mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:connect(function()
	if mouse.Target ~= nil then
		if mouse.Target.Name == "Grass" then
			print'grass'
			mouse.Target:Destroy()
		end
	end
end



If you did want to structure it the way you had with a while loop, it would look like this:

local mouseClick = false;
mouse.Button1Down:connect(function()
	mouseClick = true;
end);

function update()
	local target = mouse.Target;
	if mouseClick then
		if target and target.Name == "Grass" then
			target:Destroy()
		end
	end
	mouseClick = false; -- Only last for one frame
end

while wait() do
	update()
end

Or it could look like this:

function update()
	mouse.Button1Down:wait();
	local target = mouse.Target;
	if target and target.Name == "Grass" then
		target:Destroy();
	end
end

while true do
	update()
end

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