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

How to add a text cap/limit to a text import?

Asked by 5 years ago

I've been looking everywhere on scripting helpers and I only found one answered question that was made 2 or more years ago and the script includes:

local Text = script.Parent
Text.Changed:connect(function()
    Text.Text = Text.Text:sub(1,50);
end);

I edited it to make the cap 6 by changing the 50 to 6 however it doesn't work and it just allows the user to keep applying text. I was wondering if this script is too old and not working or if it's not supposed to be used in the context I want it or in the wrong script. (At the moment I'm using the standard script.) If anyone could help me that would be a huge help to the game I'm trying to make. ~ oshawat00

0
put a print in the function and test if it prints awesomeipod 607 — 5y
0
it doesnt print oshawat00 62 — 5y
0
This is a really great question, I’d like to know too Ziffixture 6913 — 5y
0
This code is in a local script right? hellmatic 1523 — 5y

1 answer

Log in to vote
2
Answered by 5 years ago

Since the Changed event method didn't work, we would have to detect when the client presses a key on the keyboard. We could do this using InputBegan, an event from UserInputService:

local UIS = game:GetService("UserInputService")

local TextButton = script.Parent

local MaxCharacters = 50
local InputBeganConnection = nil

local function DisconnectInputBeganEvent()
    -- since events can be connected, you can cancel it by disconnecting
    -- it is important in this case since we reconnect the event when the TextButton gains focus.
    -- it'll stop events from stacking and allows us to cancel them when they're unneeded
    if InputBeganConnection then 
        InputBeganConnection:Disconnect()
        InputBeganConnection = nil
    end
end

TextButton.FocusLost:Connect(DisconnectInputBeganEvent) -- FocusLost fires when the TextButton loses selection

local function OnFocused()
    DisconnectInputBeganEvent()
    InputBeganConnection = UIS.InputBegan:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.Keyboard then 
            TextButton.Text = string.sub(TextButton.Text, 1, MaxCharacters)
            -- string.sub has 3 arguments: s(string), i, j
            -- it returns the substring of s that starts at i and continues until j
            -- for example: string.sub("Text", 3, 4) would return "xt" because
            -- 'x' is the third string and 't' is the fourth
        end
    end)
end

TextButton.Focused:Connect(OnFocused) -- the Focused event fires when the TextButton gains selection (when the user clicks the button)
Ad

Answer this question