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

Only execute a Touched command once?

Asked by 4 years ago

I have a script that executes a function that checks for a touch. However, I only want it to check for it in that moment. Instead, it checks constantly after the command is executed. I'm pretty sure I know why it does this, but I'm sure I would have to check if it's actually touching it in order to do so. How can I get it to only check if it's touching the "Target" when the "Attack()" is executed?

Here's the script:

num = script.Parent.num
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local radius = player.Character.HumanoidRootPart.HomingRadius

mouse.KeyDown:connect(function(key)
    if key:byte() == 32 and num.Value == 1 then     
        Attack()
    end
end)

function Attack()
    radius.Touched:connect(function(hit)
        if hit.Name == "Target" then
            print("I'm executing")
            --local target = radius.hit
        end
    end)
end

(Also, anyone know how to get the "hit" to use as a variable?)

0
connect is deprecated in favour of Connect, KeyDown is deprecated in favour of InputBegan and ContextActionService, the former fires for almost all inputs, and who knows maybe one of the UserInputService events/functions may be useful to you: https://developer.roblox.com/en-us/api-reference/class/UserInputService User#24403 69 — 4y
0
Btw please don't use global variables. Attack should be declared before the connect call. User#24403 69 — 4y

2 answers

Log in to vote
0
Answered by 4 years ago
num = script.Parent.num
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local radius = player.Character.HumanoidRootPart.HomingRadius
local Toggled = false

mouse.KeyDown:connect(function(key)
    if key:byte() == 32 and num.Value == 1 then     
        Attack()
    end
end)

function Attack()
    radius.Touched:connect(function(hit)
        if hit.Name == "Target" then
            if Toggled == false then
                Toggled = true
                print("I'm executing")
                --local target = radius.hit
            end
        end
    end)
end

Add a new variable called, 'Toggle' Add an if statement so when the event is called, It executes it. But then change the variable to true. This will only allow it to be called once. As the if statement will pick it up as: Toggle = true. Not Toggle = false

Ad
Log in to vote
0
Answered by 4 years ago

That almost works. I should phrase my question differently--whenever the Attack() is executed, I want it to sense if it's touching "Target"....but only in the moment when it's executed. Any other time, it shouldn't check if it's touching. This should be able to repeat, too, since Attack() can be done at any time, multiple times in a game.

Answer this question