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

How to add a function to a function?

Asked by 7 years ago

Hello there! I have a question! So I am trying to create something that if you are touching a part, it will detect your Keyboard Input but I do not fully comprehend how I can make a function trigger another function. How would I do so?

function onKeyPress(inputObject, gameProcessedEvent)
    if inputObject.KeyCode == Enum.KeyCode.E then
        local light = game.ReplicatedStorage.Flashlight:Clone()
        light.Parent = game.Workspace.SpawnsLights
    end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

Well if I completely understand what you are asking, to clarify, you want to detect a users input if they are touching a part?

If so, try something like this:

(When I say "something" it would just be this general concept, I am not sure if the touch works on client or if you need to check if the localplayer is the other part)

local istouching = false

local function onKeyPress(inputObject, gameProcessedEvent)
    if istouching then
        -- Your code
    end
end

local function touchStart()
    istouching = true
end

local function touchEnded()
    istouching = false
end

workspace.part.Touched:connect(touchStart)
workspace.part.TouchEnded:connect(touchEnded)
game:GetService("UserInputService").InputBegan:connect(onKeyPress)

It should be pretty straight forward, if you would like more of an explanation then just ask. If this is not what you were asking, please clarify.

Best of luck

Edit:

Possibly, another way of doing this would be:

local keypresscon = nil

local function onKeyPress(inputObject, gameProcessedEvent)
    -- your code
end

local function touchStart()
    if keypresscon ~= nil and keypresscon.Disconnect ~= nil then keypresscon:Disconnect() end
    keypresscon = game:GetService("UserInputService").InputBegan:connect(onKeyPress)
end

local function touchEnded()
    if keypresscon ~= nil and keypresscon.Disconnect ~= nil then keypresscon:Disconnect() end
end

workspace.part.Touched:connect(touchStart)
workspace.part.TouchEnded:connect(touchEnded)

This would just create the connection when the player starts touching the part, and then destroy it when it ends, pretty straight forward, again. All of this is untested. Sorry for any bugs

0
Thank you. I have tested it, added an extra end to it but it works! Thank you! BunnyFilms1 297 — 7y
0
Of course! Gamprofwiesonel 31 — 7y
Ad

Answer this question