使用“FindFirstChild”和“WaitForChild”获取 NIL
2020-10-22 9:29:41
收藏:0
阅读:100
评论:1
我正在尝试一个名为 Roblox Lua: Scripting For Beginners Leaderboard Script-Through 的书籍中的实例。 我遇到了错误。错误消息是“Workspace.Part.Script:4: attempt to index nil with 'WaitForChild'”。我还遇到了相同的错误信息,用于 FindFirstChild。
这是排行榜脚本:
game.Players.PlayerAdded:Connect(function (player)
stats = Instance.new("IntValue")
stats.Parent = player
stats.Name = "leaderstats"
points = Instance.new("IntValue")
points.Parent = stats
points.Name = "Points"
deaths = Instance.new("IntValue")
deaths.Parent = stats
deaths.Name = "Deaths"
end)
这是我作为硬币创建的部分的脚本:
script.Parent.Touched:Connect(function()
player = game:GetService("Players").LocalPlayer
stats = player:WaitForChild("leaderstats")
points = stats:findFirstChild("Points")
points.Value = points.Value + 1
script.Parent:Destroy()
end)
当您踩在这个硬币上时,它应该将一个点添加到点列中。我试图使用 FindFirstChild 但我一直收到 NIL 异常,我无法弄清原因。我已经做了一些研究,但似乎所有我研究的东西都比我的问题更复杂。当我加载到游戏中时,排行榜确实出现了。列(Points)也出现了。有什么建议吗?
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

好的,有几件事情你必须改变才能让这段代码正常运行,让我来帮助你。
就像Alexander所说,你需要在变量中使用local关键字,并且给int类型的变量声明初始值。我的建议是使用Instance.new("IntValue",parent)代替换行。另外,在leaderstats中最好使用文件夹而不是值。
game.Players.PlayerAdded:Connect(function (player) local stats = Instance.new("Folder",player) stats.Name = "leaderstats" local points = Instance.new("IntValue",stats) points.Value = 0 points.Name = "Points" local deaths = Instance.new("IntValue",stats) deaths.Value = 0 deaths.Name = "Deaths" end)对于触碰部分,主要的问题在于你始终会得到nil,因为你没有接收触碰参数。你可能想将这个脚本放在服务器端,而不是在本地脚本中,并且不要使用localplayer,否则它在服务器上没有任何效果,并且没有人能够获得点数。
script.Parent.Touched:Connect(function(hit) --hit是触碰到的部分 player = game.Players:FindFirstChild(hit.Parent.Name) --寻找该部分的父对象名称 if player then --检测是否触碰到的是玩家 local stats = player:WaitForChild("leaderstats") local points = stats:FindFirstChild("Points") points.Value = points.Value + 1 script.Parent:Destroy() end end)