Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
Teeter11 281 Moderation Voter
10 years ago

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

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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
Ad

Answer this question