TextBox
*Ce contenu est traduit en utilisant l'IA (Beta) et peut contenir des erreurs. Pour consulter cette page en anglais, clique ici.
Un boîte de texte permet au joueur de fournir une entrée de texte.Il se comporte de manière similaire à un TextButton , sauf que une seule boîte de texte peut être mise en évidence en cliquant, en tapant ou en sélectionnant une manette de jeu.Pendant le focus, le joueur peut utiliser un clavier pour modifier la propriété Text.
- S'il n'y a pas de texte, le PlaceholderText sera visible. Cela est utile pour inciter les joueurs du type ou du format de données qu'ils doivent saisir.
- Par défaut, la propriété ClearTextOnFocus est activée et garantit qu'il n'y a pas de texte existant lorsque une boîte de texte est mise en évidence.Cela peut ne pas être souhaitable pour le texte qui devrait être modifiable par le joueur.
- La propriété MultiLine permet aux joueurs d'entrer plusieurs lignes de texte avec des caractères de saut de ligne ( \n ).
Le ContextActionService honore les raccourcis clavier de la boîte de texte et empêchera automatiquement la transmission d'événements de pression de clé aux actions liées à ContextActionService:BindAction().UserInputService.InputBegan et les événements associés se déclencheront toujours lorsqu'une boîte de texte est en focus.
État de concentration
Il est possible de détecter et de modifier l'état de concentration d'une TextBox :
- Vous pouvez utiliser CaptureFocus lorsqu'un dialogue apparaît afin que le joueur n'ait pas à cliquer sur une boîte de texte lorsqu'elle devient disponible ; vous pouvez utiliser ContextActionService:BindAction() pour lier une certaine clé à la concentration d'une boîte de texte en utilisant cette fonction.Lorsqu'une TextBox entre en focus, l'événement Focused se déclenche.
- Vous pouvez détecter si une certaine boîte de texte est en focus en utilisant IsFocused . Alternativement, UserInputService:GetFocusedTextBox() peut être utilisée pour vérifier si une boîte de texte est en focus.
- Lorsque le joueur a terminé l'entrée de texte, l'événement FocusLost se déclenche, indiquant si l'utilisateur a appuyé sur Enter pour soumettre du texte avec le InputObject qui a causé la perte de concentration.Lors de l'utilisation de claviers sur écran sur mobile et console, ReturnPressedFromOnScreenKeyboard peut également se lancer.
- Si une question plus importante se présente pendant le partie, vous pouvez ReleaseFocus de la boîte de texte afin que l'entrée du clavier d'un joueur revienne dans votre jeu.
Édition de texte
Un TextBox prend en charge la sélection de texte via ses propriétés CursorPosition et SelectionStart.En utilisant GetPropertyChangedSignal, vous pouvez détecter quand une sélection change.En outre, il est possible pour les joueurs de copier et coller du texte dans une boîte de texte, ce qui permet de prendre en charge le presse-papiers assistance.
Avis de filtrage du texte Les jeux qui facilitent la communication entre joueurs en utilisant du texte, tels que le chat personnalisé ou les balises de nom, doivent filtrer correctement ce texte en utilisant TextService:FilterStringAsync() ou Chat:FilterStringAsync() .Si cela n'est pas fait correctement, votre jeu peut recevoir une action de modération.
Échantillons de code
This code sample creates a password-like interface for a TextBox, giving visual feedback on the player's input.
-- Place this code in a LocalScript inside a TextBox
local textBox = script.Parent
local secretWord = "roblox"
local colorNormal = Color3.new(1, 1, 1) -- white
local colorWrong = Color3.new(1, 0, 0) -- red
local colorCorrect = Color3.new(0, 1, 0) -- green
-- Initialize the state of the textBox
textBox.ClearTextOnFocus = true
textBox.Text = ""
textBox.Font = Enum.Font.Code
textBox.PlaceholderText = "What is the secret word?"
textBox.BackgroundColor3 = colorNormal
local function onFocused()
textBox.BackgroundColor3 = colorNormal
end
local function onFocusLost(enterPressed, _inputObject)
if enterPressed then
local guess = textBox.Text
if guess == secretWord then
textBox.Text = "ACCESS GRANTED"
textBox.BackgroundColor3 = colorCorrect
else
textBox.Text = "ACCESS DENIED"
textBox.BackgroundColor3 = colorWrong
end
else
-- The player stopped editing without pressing Enter
textBox.Text = ""
textBox.BackgroundColor3 = colorNormal
end
end
textBox.FocusLost:Connect(onFocusLost)
textBox.Focused:Connect(onFocused)
Résumé
Propriétés
Détermine si le clic sur la zone de texte effacera sa propriété TextBox.Text.
Détermine le décalage du curseur de texte en octets, ou -1 s'il n'y a pas de curseur.
Détermine la police utilisée pour rendre le texte.
Détermine la police utilisée pour rendre le texte.
Échelle l'espacement entre les lignes de texte dans le TextBox.
Le nombre maximum de graphèmes que le TextBox peut afficher.
Lorsqu'il est défini sur vrai, le texte à l'intérieur d'une TextBox peut se déplacer sur plusieurs lignes. Cela permet également aux joueurs d'utiliser la touche Entrée pour se déplacer sur une nouvelle ligne.
Définit la couleur du texte qui est utilisée lorsqu'aucun texte n'a encore été saisi dans la zone de texte.
Définit le texte qui s'affiche lorsque aucun texte n'a encore été saisi dans la zone de texte.
Détermine si la TextBox rend le texte TextBox.Text en utilisant la mise en forme de texte enrichi.
Détermine la position de départ d'une sélection de texte, ou -1 si aucun texte n'est sélectionné.
Si la valeur est définie sur vrai, l'entrée native de la plate-forme est utilisée à la place du clavier intégré de Roblox.
Détermine la chaîne rendue par l'élément UI.
La taille du texte d'un élément d'interface utilisateur en décalage.
Détermine la couleur du texte rendu.
Détermine si l'utilisateur peut modifier le Text .
Si le texte se trouve dans les contraintes de la boîte de texte.
Change si le texte est redimensionné pour s'adapter à l'objet GUI qui le rend.
Déterminez la hauteur de la ligne du texte en décalage.
Détermine la couleur du trait de texte (contour).
Détermine la transparence du trait de texte (contour).
Détermine la transparence du texte rendu.
Contrôle la troncation du texte affiché dans cette boîte de texte.
Détermine si le texte s'enroule sur plusieurs lignes dans l'espace élémentaire GuiObject, tronquant le texte en excès.
Détermine l'alignement horizontal du texte rendu.
Détermine l'alignement vertical du texte rendu.
Propriétés
Détermine si cet élément d'interface utilisateur coule l'entrée.
Détermine le point d'origine d'un GuiObject , par rapport à sa taille absolue.
Détermine si la redimensionisation se produit en fonction du contenu de l'enfant.
Détermine la couleur de fond GuiObject.
Détermine la transparence du fond et des bords GuiObject.
Détermine la couleur de la bordure GuiObject.
Détermine de quelle manière la bordure GuiObject est disposée par rapport à ses dimensions.
Détermine la largeur des pixels de la bordure GuiObject.
Détermine si le descendant GuiObjects en dehors des limites d'un élément GUI parent doit s'rendu.
Détermine si la souris du joueur est activement pressée sur le GuiObject ou non.
Détermine si la GuiButton peut être interagie ou non, ou si la GuiState du GuiObject change ou non.
Contrôle l'ordre de tri des GuiObject lorsqu'ils sont utilisés avec un UIGridStyleLayout .
Définit le GuiObject qui sera sélectionné lorsque le sélecteur de manette sera déplacé vers le bas.
Définit le GuiObject qui sera sélectionné lorsque le sélecteur de manette sera déplacé à gauche.
Définit le GuiObject qui sera sélectionné lorsque le sélecteur de manette sera déplacé à droite.
Définit le GuiObject qui sera sélectionné lorsque le sélecteur de manette sera déplacé vers le haut.
Détermine la position pixelaire et vectorielle du GuiObject .
Détermine le nombre de degrés par lesquels le GuiObject est pivoté.
Déterminez si le GuiObject peut être sélectionné par une manette de jeu.
Annule la décoration de sélection par défaut utilisée pour les gamepads.
L'ordre de GuiObjects sélectionné par la sélection de l'interface de jeu.
Détermine la taille des pixels et des échelles du GuiObject .
Définit les axes Size sur lesquels la GuiObject sera basée, par rapport à la taille de son parent.
Une propriété mixée de BackgroundTransparency et TextTransparency.
Détermine si le GuiObject et ses descendants seront rendus.
Détermine l'ordre dans lequel un GuiObject rendu se rapporte aux autres.
Propriétés
Décrit la position réelle d'un élément GuiBase2d sur l'écran, en pixels.
Décrit la rotation réelle de l'écran d'un élément GuiBase2d en degrés.
Décrit la taille réelle de l'écran d'un élément GuiBase2d, en pixels.
Lorsqu'il est défini à true, la localisation sera appliquée à ce GuiBase2d et à ses descendants.
Une référence à un LocalizationTable à utiliser pour appliquer une localisation automatisée à ce GuiBase2d et à ses descendants.
Personnalise le comportement de sélection du manette de jeu dans la direction descendante.
Personnalise le comportement de sélection du manette de jeu dans la direction de gauche.
Personnalise le comportement de sélection du gamepad dans la bonne direction.
Personnalise le comportement de sélection du gamepad dans la direction vers le haut.
Permet la personnalisation du mouvement de sélection du gamepad.
Méthodes
Force le client à se concentrer sur la zone de texte.
Renvoie vrai si la zone de texte est mise en évidence, ou faux si elle ne l'est pas.
Force le client à dé focuser la zone de texte.
Méthodes
- TweenPosition(endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
Déplace doucement une GUI vers une nouvelle UDim2.
- TweenSize(endSize : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
Redimensionne sans problème un GuiObject à un nouveau UDim2.
- TweenSizeAndPosition(endSize : UDim2,endPosition : UDim2,easingDirection : Enum.EasingDirection,easingStyle : Enum.EasingStyle,time : number,override : boolean,callback : function):boolean
Déplace doucement une interface graphique à une nouvelle taille et position.
Événements
S'enflamme lorsque le client laisse son focus quitter le TextBox.
S'enflamme lorsque le TextBox gagne du focus.
Événements
Tiré lorsqu'un utilisateur commence à interagir via un appareil d'interface humain-ordinateur (bouton de souris vers le bas, toucher début, bouton de clavier vers le bas, etc).
Tiré lorsqu'un utilisateur modifie la façon dont il interagit via un appareil d'interface homme-ordinateur (bouton de souris vers le bas, toucher début, bouton de clavier vers le bas, etc.).
Tiré lorsqu'un utilisateur cesse d'interagir via un appareil d'interface humain-ordinateur (bouton de souris vers le bas, toucher début, bouton du clavier vers le bas, etc).
Se déclenche lorsqu'un utilisateur déplace sa souris dans un élément GUI.
Se déclenche lorsqu'un utilisateur déplace sa souris en dehors d'un élément GUI.
Se déclenche chaque fois qu'un utilisateur déplace sa souris alors qu'elle se trouve à l'intérieur d'un élément GUI.
Se déclenche lorsqu'un utilisateur fait défiler la molette de sa souris en arrière lorsque la souris se trouve sur un élément de l'interface graphique.
Se déclenche lorsqu'un utilisateur fait défiler sa molette de souris vers l'avant lorsque la souris se trouve sur un élément de l'interface graphique.
Tiré lorsque l'objet Gui est mis en évidence avec le sélecteur de manette.
Tiré lorsque le sélecteur de manette arrête de se concentrer sur l'objet Gui.
Se déclenche lorsque le joueur commence, continue et s'arrête en appuyant longuement sur l'élément d'interface utilisateur.
- TouchPan(touchPositions : Array,totalTranslation : Vector2,velocity : Vector2,state : Enum.UserInputState):RBXScriptSignal
Se déclenche lorsque le joueur déplace son doigt sur l'élément d'interface utilisateur.
- TouchPinch(touchPositions : Array,scale : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
Se déclenche lorsque le joueur effectue une gestuelle de pinçage ou de tirage à l'aide de deux doigts sur l'élément d'interface.
- TouchRotate(touchPositions : Array,rotation : number,velocity : number,state : Enum.UserInputState):RBXScriptSignal
Se déclenche lorsque le joueur effectue une gestuelle de rotation à l'aide de deux doigts sur l'élément d'interface utilisateur.
Se déclenche lorsque le joueur effectue une gestuelle de glissement sur l'élément d'interface utilisateur.
S'enflamme lorsque le joueur effectue une gestuelle de tap sur l'élément d'interface.
Événements
- SelectionChanged(amISelected : boolean,previousSelection : GuiObject,newSelection : GuiObject):RBXScriptSignal
Se déclenche lorsque la sélection de la manette de jeu se déplace, quitte ou change dans le connecteur GuiBase2d ou dans n'importe quel descendant GuiObjects.
Propriétés
ClearTextOnFocus
ContentText
CursorPosition
Échantillons de code
local textBox = script.Parent
local function showSelection()
if textBox.CursorPosition == -1 or textBox.SelectionStart == -1 then
print("No selection")
else
local selectedText = string.sub(
textBox.Text,
math.min(textBox.CursorPosition, textBox.SelectionStart),
math.max(textBox.CursorPosition, textBox.SelectionStart)
)
print('The selection is:"', selectedText, '"')
end
end
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(showSelection)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(showSelection)
Font
Échantillons de code
local textLabel = script.Parent
while true do
-- Iterate over all the different fonts
for _, font in pairs(Enum.Font:GetEnumItems()) do
textLabel.Font = font
textLabel.Text = font.Name
task.wait(1)
end
end
local frame = script.Parent
-- Créer une balise de texte affichant chaque police
for _, font in pairs(Enum.Font:GetEnumItems()) do
local textLabel = Instance.new("TextLabel")
textLabel.Name = font.Name
-- Définir les propriétés du texte
textLabel.Text = font.Name
textLabel.Font = font
-- Certaines propriétés de rendu
textLabel.TextSize = 24
textLabel.TextXAlignment = Enum.TextXAlignment.Left
-- Taillez le cadre égal à la hauteur du texte
textLabel.Size = UDim2.new(1, 0, 0, textLabel.TextSize)
-- Ajouter à la fenêtre parent
textLabel.Parent = frame
end
-- Organiser les cadres dans une liste (s'ils ne le sont pas déjà)
if not frame:FindFirstChildOfClass("UIListLayout") then
local uiListLayout = Instance.new("UIListLayout")
uiListLayout.Parent = frame
end
FontFace
LineHeight
MaxVisibleGraphemes
MultiLine
OpenTypeFeatures
OpenTypeFeaturesError
PlaceholderColor3
PlaceholderText
RichText
SelectionStart
Échantillons de code
local textBox = script.Parent
local function showSelection()
if textBox.CursorPosition == -1 or textBox.SelectionStart == -1 then
print("No selection")
else
local selectedText = string.sub(
textBox.Text,
math.min(textBox.CursorPosition, textBox.SelectionStart),
math.max(textBox.CursorPosition, textBox.SelectionStart)
)
print('The selection is:"', selectedText, '"')
end
end
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(showSelection)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(showSelection)
ShowNativeInput
Text
Échantillons de code
local TweenService = game:GetService("TweenService")
local textLabel = script.Parent
local content = {
"Welcome to my game!",
"Be sure to have fun!",
"Please give suggestions!",
"Be nice to other players!",
"Don't grief other players!",
"Check out the shop!",
"Tip: Don't die!",
}
local tweenInfo = TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
local RNG = Random.new()
local fadeIn = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 0,
})
local fadeOut = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 1,
})
local lastIndex
while true do
-- Step 0: Fade out before doing anything
fadeOut:Play()
task.wait(tweenInfo.Time)
-- Step 1: pick content that wasn't the last displayed
local index
repeat
index = RNG:NextInteger(1, #content)
until lastIndex ~= index
-- Make sure we don't show the same thing next time
lastIndex = index
-- Step 2: show the content
textLabel.Text = content[index]
fadeIn:Play()
task.wait(tweenInfo.Time + 1)
end
local textLabel = script.Parent
textLabel.Text = "Kaboom!"
while true do
for size = 5, 100, 5 do
textLabel.TextSize = size
textLabel.TextTransparency = size / 100
task.wait()
end
task.wait(1)
end
local frame = script.Parent
-- Créer une balise de texte affichant chaque police
for _, font in pairs(Enum.Font:GetEnumItems()) do
local textLabel = Instance.new("TextLabel")
textLabel.Name = font.Name
-- Définir les propriétés du texte
textLabel.Text = font.Name
textLabel.Font = font
-- Certaines propriétés de rendu
textLabel.TextSize = 24
textLabel.TextXAlignment = Enum.TextXAlignment.Left
-- Taillez le cadre égal à la hauteur du texte
textLabel.Size = UDim2.new(1, 0, 0, textLabel.TextSize)
-- Ajouter à la fenêtre parent
textLabel.Parent = frame
end
-- Organiser les cadres dans une liste (s'ils ne le sont pas déjà)
if not frame:FindFirstChildOfClass("UIListLayout") then
local uiListLayout = Instance.new("UIListLayout")
uiListLayout.Parent = frame
end
local textLabel = script.Parent
-- This text wrapping demo is best shown on a 200x50 px rectangle
textLabel.Size = UDim2.new(0, 200, 0, 50)
-- Some content to spell out
local content = "Here's a long string of words that will "
.. "eventually exceed the UI element's width "
.. "and form line breaks. Useful for paragraphs "
.. "that are really long."
-- A function that will spell text out two characters at a time
local function spellTheText()
-- Iterate from 1 to the length of our content
for i = 1, content:len() do
-- Get a substring of our content: 1 to i
textLabel.Text = content:sub(1, i)
-- Color the text if it doesn't fit in our box
if textLabel.TextFits then
textLabel.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textLabel.TextColor3 = Color3.new(1, 0, 0) -- Red
end
-- Wait a brief moment on even lengths
if i % 2 == 0 then
task.wait()
end
end
end
while true do
-- Spell the text with scale/wrap off
textLabel.TextWrapped = false
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with wrap on
textLabel.TextWrapped = true
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with text scaling on
-- Note: Text turns red (TextFits = false) once text has to be
-- scaled down in order to fit within the UI element.
textLabel.TextScaled = true
-- Note: TextWrapped is enabled implicitly when TextScaled = true
--textLabel.TextWrapped = true
spellTheText()
task.wait(1)
end
local textLabel = script.Parent
local moods = {
["happy"] = "😃",
["sad"] = "😢",
["neutral"] = "😐",
["tired"] = "😫",
}
while true do
for mood, face in pairs(moods) do
textLabel.Text = "I am feeling " .. mood .. "! " .. face
task.wait(1)
end
end
TextBounds
Échantillons de code
local textBox = script.Parent
-- The smallest the TextBox will go
local minWidth, minHeight = 10, 10
-- Set alignment so our text doesn't wobble a bit while we type
textBox.TextXAlignment = Enum.TextXAlignment.Left
textBox.TextYAlignment = Enum.TextYAlignment.Top
local function updateSize()
textBox.Size = UDim2.new(0, math.max(minWidth, textBox.TextBounds.X), 0, math.max(minHeight, textBox.TextBounds.Y))
end
textBox:GetPropertyChangedSignal("TextBounds"):Connect(updateSize)
TextColor3
Échantillons de code
local textBox = script.Parent
local function hasVowels(str)
return str:lower():find("[aeiou]")
end
local function onTextChanged()
local text = textBox.Text
-- Check for vowels
if hasVowels(text) then
textBox.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textBox.TextColor3 = Color3.new(1, 0, 0) -- Red
end
end
textBox:GetPropertyChangedSignal("Text"):Connect(onTextChanged)
-- Place this code in a LocalScript inside a TextBox
local textBox = script.Parent
local secretWord = "roblox"
local colorNormal = Color3.new(1, 1, 1) -- white
local colorWrong = Color3.new(1, 0, 0) -- red
local colorCorrect = Color3.new(0, 1, 0) -- green
-- Initialize the state of the textBox
textBox.ClearTextOnFocus = true
textBox.Text = ""
textBox.Font = Enum.Font.Code
textBox.PlaceholderText = "What is the secret word?"
textBox.BackgroundColor3 = colorNormal
local function onFocused()
textBox.BackgroundColor3 = colorNormal
end
local function onFocusLost(enterPressed, _inputObject)
if enterPressed then
local guess = textBox.Text
if guess == secretWord then
textBox.Text = "ACCESS GRANTED"
textBox.BackgroundColor3 = colorCorrect
else
textBox.Text = "ACCESS DENIED"
textBox.BackgroundColor3 = colorWrong
end
else
-- The player stopped editing without pressing Enter
textBox.Text = ""
textBox.BackgroundColor3 = colorNormal
end
end
textBox.FocusLost:Connect(onFocusLost)
textBox.Focused:Connect(onFocused)
-- Place this code in a LocalScript within a TextLabel/TextButton
local textLabel = script.Parent
-- Some colors we'll use with TextColor3
local colorNormal = Color3.new(0, 0, 0) -- black
local colorSoon = Color3.new(1, 0.5, 0.5) -- red
local colorDone = Color3.new(0.5, 1, 0.5) -- green
-- Loop infinitely
while true do
-- Count backwards from 10 to 1
for i = 10, 1, -1 do
-- Set the text
textLabel.Text = "Time: " .. i
-- Set the color based on how much time is left
if i > 3 then
textLabel.TextColor3 = colorNormal
else
textLabel.TextColor3 = colorSoon
end
task.wait(1)
end
textLabel.Text = "GO!"
textLabel.TextColor3 = colorDone
task.wait(2)
end
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Placez une valeur de chaîne appelée « GameState » dans le stockage répliqué
local vGameState = ReplicatedStorage:WaitForChild("GameState")
-- Placez ce code dans une balise de texte
local textLabel = script.Parent
-- Certaines couleurs que nous utiliserons avec TextColor3
local colorNormal = Color3.new(0, 0, 0) -- noir
local colorCountdown = Color3.new(1, 0.5, 0) -- orange
local colorRound = Color3.new(0.25, 0.25, 1) -- bleu
-- Nous exécuterons cette fonction pour mettre à jour le TextLabel en tant qu'état du
-- changements de jeu.
local function update()
-- Mise à jour du texte
textLabel.Text = "State: " .. vGameState.Value
-- Définir la couleur du texte en fonction de l'état du jeu actuel
if vGameState.Value == "Countdown" then
textLabel.TextColor3 = colorCountdown
elseif vGameState.Value == "Round" then
textLabel.TextColor3 = colorRound
else
textLabel.TextColor3 = colorNormal
end
end
-- Motif : mise à jour une fois lorsque nous commençons et également lorsque vGameState change
-- Nous devrions toujours voir le GameState le plus récent.
update()
vGameState.Changed:Connect(update)
TextDirection
TextEditable
TextFits
TextScaled
Échantillons de code
local textLabel = script.Parent
-- This text wrapping demo is best shown on a 200x50 px rectangle
textLabel.Size = UDim2.new(0, 200, 0, 50)
-- Some content to spell out
local content = "Here's a long string of words that will "
.. "eventually exceed the UI element's width "
.. "and form line breaks. Useful for paragraphs "
.. "that are really long."
-- A function that will spell text out two characters at a time
local function spellTheText()
-- Iterate from 1 to the length of our content
for i = 1, content:len() do
-- Get a substring of our content: 1 to i
textLabel.Text = content:sub(1, i)
-- Color the text if it doesn't fit in our box
if textLabel.TextFits then
textLabel.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textLabel.TextColor3 = Color3.new(1, 0, 0) -- Red
end
-- Wait a brief moment on even lengths
if i % 2 == 0 then
task.wait()
end
end
end
while true do
-- Spell the text with scale/wrap off
textLabel.TextWrapped = false
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with wrap on
textLabel.TextWrapped = true
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with text scaling on
-- Note: Text turns red (TextFits = false) once text has to be
-- scaled down in order to fit within the UI element.
textLabel.TextScaled = true
-- Note: TextWrapped is enabled implicitly when TextScaled = true
--textLabel.TextWrapped = true
spellTheText()
task.wait(1)
end
TextSize
Échantillons de code
local textLabel = script.Parent
textLabel.Text = "Kaboom!"
while true do
for size = 5, 100, 5 do
textLabel.TextSize = size
textLabel.TextTransparency = size / 100
task.wait()
end
task.wait(1)
end
TextStrokeColor3
Échantillons de code
local textLabel = script.Parent
-- How fast the highlight ought to blink
local freq = 2
-- Set to yellow highlight color
textLabel.TextStrokeColor3 = Color3.new(1, 1, 0)
while true do
-- math.sin oscillates from -1 to 1, so we change the range to 0 to 1:
local transparency = math.sin(workspace.DistributedGameTime * math.pi * freq) * 0.5 + 0.5
textLabel.TextStrokeTransparency = transparency
task.wait()
end
TextStrokeTransparency
Échantillons de code
local textLabel = script.Parent
-- How fast the highlight ought to blink
local freq = 2
-- Set to yellow highlight color
textLabel.TextStrokeColor3 = Color3.new(1, 1, 0)
while true do
-- math.sin oscillates from -1 to 1, so we change the range to 0 to 1:
local transparency = math.sin(workspace.DistributedGameTime * math.pi * freq) * 0.5 + 0.5
textLabel.TextStrokeTransparency = transparency
task.wait()
end
TextTransparency
Échantillons de code
local TweenService = game:GetService("TweenService")
local textLabel = script.Parent
local content = {
"Welcome to my game!",
"Be sure to have fun!",
"Please give suggestions!",
"Be nice to other players!",
"Don't grief other players!",
"Check out the shop!",
"Tip: Don't die!",
}
local tweenInfo = TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
local RNG = Random.new()
local fadeIn = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 0,
})
local fadeOut = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 1,
})
local lastIndex
while true do
-- Step 0: Fade out before doing anything
fadeOut:Play()
task.wait(tweenInfo.Time)
-- Step 1: pick content that wasn't the last displayed
local index
repeat
index = RNG:NextInteger(1, #content)
until lastIndex ~= index
-- Make sure we don't show the same thing next time
lastIndex = index
-- Step 2: show the content
textLabel.Text = content[index]
fadeIn:Play()
task.wait(tweenInfo.Time + 1)
end
local textLabel = script.Parent
textLabel.Text = "Kaboom!"
while true do
for size = 5, 100, 5 do
textLabel.TextSize = size
textLabel.TextTransparency = size / 100
task.wait()
end
task.wait(1)
end
TextTruncate
TextWrapped
Échantillons de code
local textLabel = script.Parent
-- This text wrapping demo is best shown on a 200x50 px rectangle
textLabel.Size = UDim2.new(0, 200, 0, 50)
-- Some content to spell out
local content = "Here's a long string of words that will "
.. "eventually exceed the UI element's width "
.. "and form line breaks. Useful for paragraphs "
.. "that are really long."
-- A function that will spell text out two characters at a time
local function spellTheText()
-- Iterate from 1 to the length of our content
for i = 1, content:len() do
-- Get a substring of our content: 1 to i
textLabel.Text = content:sub(1, i)
-- Color the text if it doesn't fit in our box
if textLabel.TextFits then
textLabel.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textLabel.TextColor3 = Color3.new(1, 0, 0) -- Red
end
-- Wait a brief moment on even lengths
if i % 2 == 0 then
task.wait()
end
end
end
while true do
-- Spell the text with scale/wrap off
textLabel.TextWrapped = false
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with wrap on
textLabel.TextWrapped = true
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with text scaling on
-- Note: Text turns red (TextFits = false) once text has to be
-- scaled down in order to fit within the UI element.
textLabel.TextScaled = true
-- Note: TextWrapped is enabled implicitly when TextScaled = true
--textLabel.TextWrapped = true
spellTheText()
task.wait(1)
end
TextXAlignment
Échantillons de code
-- Paste this in a LocalScript within a TextLabel/TextButton/TextBox
local textLabel = script.Parent
local function setAlignment(xAlign, yAlign)
textLabel.TextXAlignment = xAlign
textLabel.TextYAlignment = yAlign
textLabel.Text = xAlign.Name .. " + " .. yAlign.Name
end
while true do
-- Iterate over both TextXAlignment and TextYAlignment enum items
for _, yAlign in pairs(Enum.TextYAlignment:GetEnumItems()) do
for _, xAlign in pairs(Enum.TextXAlignment:GetEnumItems()) do
setAlignment(xAlign, yAlign)
task.wait(1)
end
end
end
TextYAlignment
Échantillons de code
-- Paste this in a LocalScript within a TextLabel/TextButton/TextBox
local textLabel = script.Parent
local function setAlignment(xAlign, yAlign)
textLabel.TextXAlignment = xAlign
textLabel.TextYAlignment = yAlign
textLabel.Text = xAlign.Name .. " + " .. yAlign.Name
end
while true do
-- Iterate over both TextXAlignment and TextYAlignment enum items
for _, yAlign in pairs(Enum.TextYAlignment:GetEnumItems()) do
for _, xAlign in pairs(Enum.TextXAlignment:GetEnumItems()) do
setAlignment(xAlign, yAlign)
task.wait(1)
end
end
end
Méthodes
CaptureFocus
Retours
Échantillons de code
local ContextActionService = game:GetService("ContextActionService")
local ACTION_NAME = "FocusTheTextBox"
local textBox = script.Parent
local function handleAction(actionName, inputState, _inputObject)
if actionName == ACTION_NAME and inputState == Enum.UserInputState.End then
textBox:CaptureFocus()
end
end
ContextActionService:BindAction(ACTION_NAME, handleAction, false, Enum.KeyCode.Q)
ReleaseFocus
Paramètres
Retours
Échantillons de code
local textBox = script.Parent
local function onFocused()
task.wait(5)
textBox:ReleaseFocus()
end
textBox.Focused:Connect(onFocused)
Événements
FocusLost
Paramètres
Échantillons de code
local gui = script.Parent
local textBox = gui.TextBox
local function focusLost(enterPressed)
if enterPressed then
print("Focus was lost because enter was pressed!")
else
print("Focus was lost without enter being pressed")
end
end
textBox.FocusLost:Connect(focusLost)
local textBox = script.Parent
local function onFocusLost(enterPressed, inputThatCausedFocusLost)
if enterPressed then
print("Player pressed Enter")
else
print("Player pressed", inputThatCausedFocusLost.KeyCode)
end
end
textBox.FocusLost:Connect(onFocusLost)
Focused
Échantillons de code
local textBox = script.Parent
local function onFocused()
print("Focused")
end
textBox.Focused:Connect(onFocused)