本示例演示如何使用 TextChatService 类来设计自己的前端。它重用了 CreateDefaultTextChannels 的默认文本频道,并且相较于默认 UI 非常简单。
通过在 Studio 的 属性 窗口中将 ChatWindowConfiguration.Enabled 和 ChatInputBarConfiguration.Enabled 属性设置为 false 来禁用与 TextChatService 一起提供的默认 UI。
创建聊天输入框的替代品。这是当用户按下 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("发送消息失败")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)