自訂文字聊天介面

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

這個例子顯示了如何使用 TextChatService 類來設計自己的前端。它會重複來自 CreateDefaultTextChannels 的預設文字通道,並且與預設介面相比非常簡單。

  1. 在 Studio 的 屬性窗口 設置 和 1> 屬性為 4> 以禁用與 一起提供的預設用戶介面。

  2. 創建一個聊天輸入欄的替代。這是用戶按下 Enter 時發出訊息的文字盒。

    1. 創建一個 ScreenGui 並將其作為父親 StarterGui

    2. 創建一個 TextBox 並將其作為新的 ScreenGui 的父級,然後 重新定位調整尺寸 以達到所需的效果。

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

    4. LocalScript 中添加以下代碼:

      客戶

      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("Failed to send message")
      end
      -- 使用者期望在傳送訊息後清除輸入框
      textBox.Text = ""
      end
      end)
  3. 創建一個聊天窗口的替代。這是顯示訊息的 ScrollingFrame ,它會從 TextChatService.MessageReceived 收到訊息時顯示它們。此步驟也創建一個 UIListLayout 來自動佈置訊息。

    1. 創建另一個新的 ScreenGui 並將其指派給 StarterGui

    2. 創建一個 ScrollingFrame 並將其指派給 ScreenGui ,然後 重新定位調整尺寸 以達到所需的效果。

    3. 創建一個 UIListLayout 並將其作為 ScrollingFrame 的父級。

    4. 創建一個 LocalScript 並將其作為 ScrollingFrame 的父級。

    5. LocalScript 中添加以下代碼:

      客戶

      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 聚焦或添加 聊天標籤