应用于各种来源和输入的 文本过滤 防止用户看到不当语言和个人识别信息,例如电话号码。Roblox 会自动过滤通过 体验内文本聊天 的常见文本输出,但 您需要负责过滤您没有明确控制的任何显示文本。
过滤场景
文本可以在各种场景下收集和/或显示给用户,包括:
一个体验通过随机字符生成单词并将其显示给用户,因为有可能会生成不当单词。
与外部 Web 服务器连接的体验以获取在体验中显示的内容。通常您无法控制外部站点的内容,并且第三方可以编辑该信息。
存储文本的体验,例如使用 数据存储 存储用户的宠物名字,存储的文本可能包含应在检索时进行过滤的不当单词。
过滤过程
TextService:FilterStringAsync() 通过输入文本字符串和创建文本的用户的 UserId 进行过滤体验内文本。它返回一个 TextFilterResult 对象,该对象具有两个额外的方法,您可以在不同场景中调用它们:
- TextFilterResult:GetNonChatStringForBroadcastAsync() 用于过滤对所有用户可见的文本,例如为用户提供写消息的对话框,该消息在服务器上对所有用户可见的标志上显示。
- TextFilterResult:GetNonChatStringForUserAsync() 根据年龄和其他细节向特定用户显示过滤后的文本。
在 TextBox 输入的上下文中,以下示例在 FocusLost 事件上收集输入,并通过 RemoteEvent 将其发送到服务器。在服务器上,它首先通过 FilterStringAsync() 进行过滤,然后通过 GetNonChatStringForBroadcastAsync(),目的是希望文本能显示给所有用户在服务器端对象中的内容,例如 3D 世界中的 SurfaceGui。
过滤文本输入 - 客户端脚本
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local textBox = script.Parent
textBox.ClearTextOnFocus = false
textBox.PlaceholderText = "..."
textBox.TextXAlignment = Enum.TextXAlignment.Left
textBox.TextScaled = true
-- RemoteEvent 将文本输入发送到服务器进行过滤
local inputRemoteEvent = ReplicatedStorage:FindFirstChild("InputRemoteEvent")
-- 处理焦点丢失和按下回车的事件处理程序
local function onFocusLost(enterPressed, inputObject)
if enterPressed then
print("已提交:", textBox.Text)
if inputRemoteEvent then
inputRemoteEvent:FireServer(textBox.Text)
end
end
end
textBox.FocusLost:Connect(onFocusLost)
过滤文本输入 - 服务器脚本
local TextService = game:GetService("TextService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- RemoteEvent 接收来自客户端的文本输入进行过滤
local inputRemoteEvent = ReplicatedStorage:FindFirstChild("InputRemoteEvent")
local function getFilterResult(text, fromUserId)
local filterResult
local success, errorMessage = pcall(function()
filterResult = TextService:FilterStringAsync(text, fromUserId)
end)
if success then
return filterResult
else
warn("生成 TextFilterResult 时出错:", errorMessage)
end
end
-- 当客户端提交文本框中的输入时触发
local function onInputReceived(player, text)
if text ~= "" then
local filterResult = getFilterResult(text, player.UserId)
if filterResult then
local success, filteredText = pcall(function()
return filterResult:GetNonChatStringForBroadcastAsync()
end)
if success then
print("过滤后:", filteredText)
else
warn("过滤文本时出错!")
end
end
end
end
inputRemoteEvent.OnServerEvent:Connect(onInputReceived)