尝试在 Roblox 中使用 nil 和字符串进行连接

我很困惑。我正在尝试使用 Roblox 的“ProximityPrompt”来让玩家在按住 E 键时,在屏幕上获取一个 GUI 并显示一些文本。除了无法正常显示文本外,其他一切都正常。我也没有在客户端脚本中编写字符串。在服务器脚本中,有一个对应的变量被传递。但我在输出中一直看到这个错误。

Players.ford200000.PlayerGui.BuyGui.Frame.TextInput.Text:2: attempt to concatenate nil with string - Client -

以下是我的脚本

local sp = script.Parent
sp.ProximityPrompt.Triggered:Connect(function(player)
    local name = sp.Name
    local ss = game.ServerStorage
    local item = ss.Hats:FindFirstChild(name)
    local price = item.Price
    game.ReplicatedStorage.ShopClickEvent:FireClient(player)
    game.ReplicatedStorage.ShopInfoEvent:FireClient(player)
end)

以下是用于监听 ShopInfoEvent 的本地脚本

game.ReplicatedStorage.ShopInfoEvent.OnClientEvent:Connect(function(player, price, item)
    script.Parent.Text = "您是否想花费 ".. price.Value .." 购买 ".. item.Name .."?"
end)

请帮个忙,非常感谢。

点赞
用户2860267
用户2860267

您的错误告诉您,您要添加到字符串的对象未定义。 这可能是item.Nameprice.Value未定义,导致此字符串构建失败。

查看您如何定义itemprice,这两个值在您的LocalScript回调中都未定义。当您调用RemoteEvent的FireClient函数时,第一个参数告诉引擎要将事件发送给谁,而所有其他参数都将作为回调的参数传递。当前,您根本没有传递任何参数。

因此,要解决您的问题,您需要从脚本中传递正确的参数:

game.ReplicatedStorage.ShopInfoEvent:FireClient(player, price, item)

并在您的LocalScript中正确解析它们:

game.ReplicatedStorage.ShopInfoEvent.OnClientEvent:Connect(function(price, item)
    script.Parent.Text = "Would you like to buy this ".. item.Name .." for ".. tostring(price.Value) .."?"
end)
2021-01-22 07:13:53
用户2858170
用户2858170

Players.ford200000.PlayerGui.BuyGui.Frame.TextInput.Text:2: attempt to concatenate nil with string - Client -

这里已经告诉你所有你需要知道的信息。

你试图将 nil 和字符串连接起来。这意味着你在第2行使用了字符串连接运算符 ..,但操作数为空值。

让我们看看第2行的代码:

script.Parent.Text = "Would you like to buy this ".. item.Name .." for ".. tostring(price.Value) .."?"

显然,"Would you like to buy this "" for ""?" 都是字符串。所以,剩下的就是 item.Nametostring(price.Value) 了。

如果 price.Valuenil,那么 tostring 会将其转换成字符串 "nil"。所以这不可能是这个特定错误消息的原因。

那么就只能是 item.Name 了。如果 itemnil,那我们应该看到"索引空值"的错误信息。而我们并没有看到这样的信息。因此,这说明 item 不是我们所期望的一个键为 "Name" 的表。

此时,你就知道函数的参数存在问题了。所以你(希望如此)再次参考函数手册,将其与你使用事件函数的方式进行比较。

2021-01-22 09:12:04