這個例子顯示了如何使用 TextChatService 類來設計自己的前端。它會重複來自 CreateDefaultTextChannels 的預設文字通道,並且與預設介面相比非常簡單。
在 Studio 的 屬性窗口 設置 和 1> 屬性為 4> 以禁用與 一起提供的預設用戶介面。
創建一個聊天輸入欄的替代。這是用戶按下 Enter 時發出訊息的文字盒。
創建一個 ScreenGui 並將其作為父親 StarterGui 。
創建一個 LocalScript 並將其作為新的 TextBox 的父。
在 LocalScript 中添加以下代碼:
客戶local 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("Failed to send message")end-- 使用者期望在傳送訊息後清除輸入框textBox.Text = ""endend)
創建一個聊天窗口的替代。這是顯示訊息的 ScrollingFrame ,它會從 TextChatService.MessageReceived 收到訊息時顯示它們。此步驟也創建一個 UIListLayout 來自動佈置訊息。
創建另一個新的 ScreenGui 並將其指派給 StarterGui 。
創建一個 ScrollingFrame 並將其指派給 ScreenGui ,然後 重新定位 並 調整尺寸 以達到所需的效果。
創建一個 UIListLayout 並將其作為 ScrollingFrame 的父級。
創建一個 LocalScript 並將其作為 ScrollingFrame 的父級。
在 LocalScript 中添加以下代碼:
客戶local 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)