ตัวอย่างนี้แสดงให้เห็นถึงวิธีการใช้คลาส TextChatService เพื่อออกแบบส่วนหน้าของคุณเอง โดยใช้งานช่องข้อความเริ่มต้นจาก CreateDefaultTextChannels และจะมีความเรียบง่ายมากเมื่อเปรียบเทียบกับ UI เริ่มต้น
ปิด UI เริ่มต้นที่มาพร้อมกับ TextChatService โดยการตั้งค่า ChatWindowConfiguration.Enabled และ ChatInputBarConfiguration.Enabled เป็น false ในหน้าต่าง Properties ของ Studio
สร้างการแทนที่สำหรับแถบป้อนข้อความแชท ซึ่งก็คือกล่องข้อความที่ส่งข้อความเมื่อผู้ใช้กด Enter
สร้าง ScreenGui และกำหนดให้เป็นผู้ปกครองของ StarterGui
สร้าง TextBox และกำหนดให้เป็นผู้ปกครองของ ScreenGui ใหม่ จากนั้น ปรับตำแหน่ง และ เปลี่ยนขนาด ตามที่ต้องการ
สร้าง LocalScript และกำหนดให้เป็นผู้ปกครองของ TextBox ใหม่
เพิ่มโค้ดต่อไปนี้ลงใน LocalScript:
Clientlocal 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:
Clientlocal 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)