自定义文本聊天 UI

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

本示例演示如何使用 TextChatService 类来设计自己的前端。它重用了 CreateDefaultTextChannels 的默认文本频道,并且相较于默认 UI 非常简单。

  1. 通过在 Studio 的 属性 窗口中将 ChatWindowConfiguration.EnabledChatInputBarConfiguration.Enabled 属性设置为 false 来禁用与 TextChatService 一起提供的默认 UI。

  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("发送消息失败")
      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 或添加 聊天标签,来扩展此示例。

©2026 Roblox Corporation、Roblox、Roblox 标志及 Powering Imagination 是我们在美国及其他国家或地区的注册与未注册商标。