Is there a better way of doing InputBegan and InputEnded?

I’m looping something until the user releases their mouse and instead of making an entirely new InputEnded event for something so simple, I just check if the mouse button 1 is up or not like this:

UserInputService.InputBegan:Connect(function(input, gpe)
    if gpe then return end

    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        repeat
            print("Holding down MouseButton1")
            task.wait()
        until
            not UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1)

        print("Not holding down MouseButton1 anymore")
    end
end)

But the problem is, if I do this with Enum.UserInputType.Touch, I have to make an InputEnded Event, and I feel like there is a better way of doing all this:

local debounce = true

UserInputService.InputBegan:Connect(function(input, gpe)
    if gpe then return end

    if input.UserInputType == Enum.UserInputType.Touch then
        debounce = true

        while debounce do
            print("Touching")
            task.wait()
        end
    end
end)

UserInputService.InputEnded:Connect(function(input, gpe)
    if gpe then return end

    if input.UserInputType == Enum.UserInputType.Touch then
        debounce = false
        print("Not touching anymore")
    end
end)

See how unnecessary that is? I can’t seem to find anything better than that so for now I’ll just use the second one. Any help would be appreciated

1 Like

Unfortunately (at least for myself) I don’t see any other way of doing it but I could be wrong

1 Like

ContextActionService is usually better for things like these.

2 Likes

Could you give me an example? I’m not the best with that kind of stuff

Don’t overcomplicate stuff

Two functions aren’t that bad, you can use OOP or modules to store them as part of system and then only connect to them via UserInputService, this will make your code more modular

Another idea is to have input listener for players that can fire functions accosiated with each input, then you can use ContextAction or UserInput Services to correctly fire function, example:

if InputsToFunctions[Input.KeyCode] then
    InputsToFunctions[Input.KeyCode](...)
end

In UserInputService there’s a function called UserInputService:IsKeyDown(keyCode : Enum.KeyCode) : boolean

It returns a boolean that tells you if a key is pressed down, so you can kind of combine it with other events and probably combine it into one event.

Or do what @0786ideal said, use OOP.

Not exacly OOP, but some separate script that will call functions, it can be map or OOP list or anything really, signals can replace functions and give you more freedom over what you do, but the idea is the same, you separate code into smaller units/sections to make it easier

if I would make a similar system, I would just use OOP tbh, would save a ton of time, but ig ur right.

1 Like