自訂文本聊天 UI

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

本示例展示了如何使用 TextChatService 類設計自己的前端。它重用了來自 CreateDefaultTextChannels 的默認文本頻道,並且相比於默認的 UI 非常簡單。

  1. 通過在 Studio 的 Properties 窗口中將 ChatWindowConfiguration.EnabledChatInputBarConfiguration.Enabled 屬性設置為 false,禁用隨 TextChatService 附帶的默認 UI。

  2. 創建一個聊天輸入框的替代品。這是用戶按下 Enter 時發送消息的文本框。

    1. 創建一個 ScreenGui 並將其作為父級放入 StarterGui

    2. 創建一個 TextBox 並將其作為父級放入新的 ScreenGui,然後根據需要 重新定位調整大小

    3. 創建一個 LocalScript 並將其作為父級放入新的 TextBox

    4. 將以下代碼添加到 LocalScript

      Client

      local TextChatService = game:GetService("TextChatService")
      -- RBXGeneral 是默認公共頻道
      local RBXGeneral = TextChatService:FindFirstChild("TextChannels"):WaitForChild("RBXGeneral")
      local textBox = script.Parent
      textBox.FocusLost:Connect(function(enterPressed)
      local text = textBox.Text
      if enterPressed and #text > 0 then
      local success, response = pcall(function()
      return RBXGeneral:SendAsync(textBox.Text)
      end)
      if not success then
      RBXGeneral:DisplaySystemMessage("發送消息失敗")
      end
      -- 用戶期待在發送消息後清空輸入框
      textBox.Text = ""
      end
      end)
  3. 創建聊天窗口的替代品。這是用於顯示從 TextChatService.MessageReceived 接收到的消息的 ScrollingFrame。這一步還創建了一個 UIListLayout 來自動佈局消息。

    1. 創建另一個新的 ScreenGui 並將其作為父級放入 StarterGui

    2. 創建一個 ScrollingFrame 並將其作為父級放入 ScreenGui,然後 重新定位調整大小

    3. 創建一個 UIListLayout 並將其作為父級放入 ScrollingFrame

    4. 創建一個 LocalScript 並將其作為父級放入 ScrollingFrame

    5. 將以下代碼添加到 LocalScript

      Client

      local TextChatService = game:GetService("TextChatService")
      -- 函數為每條接收到的消息創建一個新的文本標籤
      local function addMessageGui(textChatMessage: TextChatMessage)
      local isOutgoingMessage = textChatMessage.Status == Enum.TextChatMessageStatus.Sending
      local parent = script.Parent
      local originalLabel = parent:FindFirstChild(textChatMessage.MessageId)
      if originalLabel then
      originalLabel.Text = textChatMessage.Text
      originalLabel.BackgroundTransparency = if isOutgoingMessage then 0.5 else 0
      else
      local textLabel = Instance.new("TextLabel")
      textLabel.BorderSizePixel = 0
      textLabel.Font = Enum.Font.BuilderSans
      textLabel.TextSize = 18
      textLabel.TextXAlignment = Enum.TextXAlignment.Left
      textLabel.BackgroundTransparency = if isOutgoingMessage then 0.5 else 0
      textLabel.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
      textLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
      textLabel.Name = textChatMessage.MessageId
      textLabel.AutomaticSize = Enum.AutomaticSize.XY
      textLabel.Text = textChatMessage.Text
      textLabel.Parent = parent
      end
      end
      -- 開始監聽傳入消息
      TextChatService.MessageReceived:Connect(addMessageGui)
  4. 通過在聊天輸入框中發送消息來測試你的遊戲。你應該看到消息顯示在聊天窗口中。然後,你可以通過添加更多功能來擴展此示例,例如在按下按鍵時聚焦 TextBox 或添加 聊天標籤

©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。