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

How can I make different parts of a String different colors?

Asked by
nilVector 812 Moderation Voter
9 years ago

I am making a custom chat GUI, and I want to make the player who chatted's name green, and I want to make his/her message to be white.

I know there is a substring function that goes something like this:

name = stringName.sub(1, 5)

But how can I find the length of the player's name if the player's name is not 5 characters long, and how can I color that specific part of the string (the name) when displaying it in a GUI?

0
I'm not sure this is possible. You may have to make individual guis for every different name. RedCombee 585 — 9y
0
Yes, this is very possible. @RedCombee: Anything's possible on Roblox. Tkdriverx 514 — 9y

1 answer

Log in to vote
1
Answered by
Tkdriverx 514 Moderation Voter
9 years ago

First of all, this code needs to be run on the client (LocalScript). This has to have a RemoteEvent fired by the server.

-- 'frame' is inputted as the frame containing the player and message text label.
function format(player, message, frame)
    local name = frame:WaitForChild("PlayerName")
    local text = frame:WaitForChild("ChatText")

    name.Size = UDim2.new(100, 0, 1, 0) -- Temporary sizing. Makes sure the text fits. If not, the TextBounds will not read correctly.
    name.Text = (type(player) == "string" and player or player.Name)
    -- Here's the part that gets the length of the name:
    local nameLength = name.TextBounds.x + 6 -- The + 6 give the text some space (sometimes one character still gets cut off when ClipsDescendants or TextScaled is true).
    name.Size = UDim2.new(0, nameLength, 1, 0)
    text.Text = message
    text.Position = UDim2.new(0, nameLength, 1, 0)
end

-- Example:
format("KingedPawn", "This is a very unusual username.", script.Parent.ChatFrame1)
format(game.Players.KingedPawn, "Message", script.Parent.ChatFrame2)
0
Thank you very much! I did this in an inefficient way before reading this. I had my message on bottom (Name + Message) in white and another TextLabel with just the name on top in a different color. It looked a bit ugly, so this is better. Once again, thanks! I +1'd your Reputation! nilVector 812 — 9y
Ad

Answer this question