本示例展示了如何使用 TextChatService 類設計自己的前端。它重用了來自 CreateDefaultTextChannels 的默認文本頻道,並且相比於默認的 UI 非常簡單。
通過在 Studio 的 Properties 窗口中將 ChatWindowConfiguration.Enabled 和 ChatInputBarConfiguration.Enabled 屬性設置為 false,禁用隨 TextChatService 附帶的默認 UI。
創建一個聊天輸入框的替代品。這是用戶按下 Enter 時發送消息的文本框。
創建一個 ScreenGui 並將其作為父級放入 StarterGui。
創建一個 LocalScript 並將其作為父級放入新的 TextBox。
將以下代碼添加到 LocalScript:
Clientlocal TextChatService = game:GetService("TextChatService")-- RBXGeneral 是默認公共頻道local RBXGeneral = TextChatService:FindFirstChild("TextChannels"):WaitForChild("RBXGeneral")local textBox = script.ParenttextBox.FocusLost:Connect(function(enterPressed)local text = textBox.Textif enterPressed and #text > 0 thenlocal success, response = pcall(function()return RBXGeneral:SendAsync(textBox.Text)end)if not success thenRBXGeneral:DisplaySystemMessage("發送消息失敗")end-- 用戶期待在發送消息後清空輸入框textBox.Text = ""endend)
創建聊天窗口的替代品。這是用於顯示從 TextChatService.MessageReceived 接收到的消息的 ScrollingFrame。這一步還創建了一個 UIListLayout 來自動佈局消息。
創建另一個新的 ScreenGui 並將其作為父級放入 StarterGui。
創建一個 ScrollingFrame 並將其作為父級放入 ScreenGui,然後 重新定位 和 調整大小。
創建一個 UIListLayout 並將其作為父級放入 ScrollingFrame。
創建一個 LocalScript 並將其作為父級放入 ScrollingFrame。
將以下代碼添加到 LocalScript:
Clientlocal TextChatService = game:GetService("TextChatService")-- 函數為每條接收到的消息創建一個新的文本標籤local function addMessageGui(textChatMessage: TextChatMessage)local isOutgoingMessage = textChatMessage.Status == Enum.TextChatMessageStatus.Sendinglocal parent = script.Parentlocal originalLabel = parent:FindFirstChild(textChatMessage.MessageId)if originalLabel thenoriginalLabel.Text = textChatMessage.TextoriginalLabel.BackgroundTransparency = if isOutgoingMessage then 0.5 else 0elselocal textLabel = Instance.new("TextLabel")textLabel.BorderSizePixel = 0textLabel.Font = Enum.Font.BuilderSanstextLabel.TextSize = 18textLabel.TextXAlignment = Enum.TextXAlignment.LefttextLabel.BackgroundTransparency = if isOutgoingMessage then 0.5 else 0textLabel.BackgroundColor3 = Color3.fromRGB(0, 0, 0)textLabel.TextColor3 = Color3.fromRGB(255, 255, 255)textLabel.Name = textChatMessage.MessageIdtextLabel.AutomaticSize = Enum.AutomaticSize.XYtextLabel.Text = textChatMessage.TexttextLabel.Parent = parentendend-- 開始監聽傳入消息TextChatService.MessageReceived:Connect(addMessageGui)