自定义文本聊天界面

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

这个例子显示了如何使用 TextChatService 类来设计自己的前端。它重用了默认文本通道 CreateDefaultTextChannels 并且与默认 UI 相比很简单。

  1. 通过在 Studio 的 TextChatService 窗口设置 ChatWindowConfiguration.EnabledChatInputBarConfiguration.Enabledfalse 来禁用带有 属性 的默认用户界面。

  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 聚焦或添加 聊天标签 来扩展此示例。