文本过滤

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

应用于各种来源和输入,文本过滤 可以防止用户看到不当语言和个人可识别信息,例如电话号码。Roblox 会自动过滤常见的文本输出,例如通过 游戏内文本聊天 发送的消息,但 您有责任过滤任何您没有明确控制的显示文本

过滤场景

文本可以在多种场景中收集和/或显示给用户,包括:

  • 一个通过 TextBox 输入收集用户的 文本输入 的游戏,或者一个带有按钮的自定义 GUI,例如键盘/数字键盘界面,或 3D 空间中的交互式键盘模型。

  • 一个从随机字符生成单词并将其显示给用户的游戏,因为它有可能生成不当单词。

  • 一个连接到外部网络服务器以获取在游戏中显示的内容的游戏。通常,您无法控制外部网站的内容,第三方可以编辑信息。

  • 一个使用 数据存储 存储文本的游戏,例如用户的宠物名称,其中存储的文本可能包含在检索时应过滤的不当单词。

过滤过程

TextService:FilterStringAsync() 通过接受一段文本字符串和创建该文本的用户的 UserId 作为输入来过滤游戏内文本。它返回一个 TextFilterResult 对象,该对象具有两个额外的方法,您可以在不同场景中调用:

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
-- 当客户端提交来自 TextBox 的输入时触发
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)
©2026 Roblox Corporation、Roblox、Roblox 标志及 Powering Imagination 是我们在美国及其他国家或地区的注册与未注册商标。