scripting - 这个脚本怎么知道'currentPlayer'是谁?
问题描述
我是 Roblox 开发的新手,但想尝试制作 Asteroids 游戏。我开始为宇宙飞船创建座位,但我认识到一些我无法解释的行为,并希望有人能提供一些澄清。
这是我正在谈论的代码,只是一些非常基本的东西,所以我可以掌握一些开始的想法:
--Services--
local Players = game:GetService("Players")
--Local Variables--
local seat = script.Parent -- Refers to the VehicleSeat object
local currentPlayer = nil -- Prevents errors in reference to nil?
local prompt = script.Parent.GetInPrompt -- Get the parent object's proximity prompt
--Proximity Prompt Trigger Code--
prompt.Triggered:Connect(function(currentPlayer) -- Bind the prompt trigger to function
local char = currentPlayer.Character -- Get the currentPlayer
seat:Sit(char.Humanoid) -- Make them sit
prompt.Enabled = false -- Disable the prompt so it isn't visible
print("Character is sitting") -- Print to console for debug
end)
--Get up function--
local function gettingUp(currentPlayer)
print("Attribute Change Fired - Getting Up") -- Print to console for debug
prompt.Enabled = true
end
-- Note that since Lua is an interpreted language any function must be defined before use--
seat.ChildRemoved:Connect(function()
gettingUp(currentPlayer)
end)
我看到我访问了顶部的“Players”服务,并将 currentPlayer 变量初始化为 nil。我不明白当proximityPrompt 触发时currentPlayer 如何从nil 变为播放器。
我认为这可能是 Roblox 中的“保留名称”,但我在网上找不到任何证据。
解决方案
您的脚本将局部变量与函数参数混淆了。
在脚本的顶部,您已经定义了局部变量currentPlayer
. ProximityPrompt.Triggered信号将激活它的Player实例作为函数参数提供。你也命名了那个论点currentPlayer
。当在这个函数的范围内时,函数参数隐藏了局部变量,这意味着currentPlayer
引用这个函数参数,而不是你在脚本顶部定义的局部变量。
为了避免这种混淆,将函数参数和局部变量命名为不同的东西通常是一种很好的做法。
如果要currentPlayer
引用与 ProximityPrompt 交互的 Player,请尝试将函数参数分配给局部变量:
prompt.Triggered:Connect(function(player)
currentPlayer = player
local char = currentPlayer.Character
seat:Sit(char.Humanoid)
prompt.Enabled = false
print("Character is sitting")
end)
这将允许您以后的函数保留对 Player 对象的引用。
推荐阅读
- gradle - 在 gradle 6.0.1 中找不到参数的方法 compileOnly()
- amazon-web-services - 如何使用 Elastic Beanstalk 和 django-cms 上传图像
- python - cv2.findContours 找不到轮廓
- python-3.x - 当没有其他python进程同时写入sqlite db数据库时,为什么会锁定它?
- c++ - 将 PrimitiveBatch::DrawIndexed 与 ID3D11DeviceContext::DrawIndexed 一起使用?
- python - 如何在 PyQt5 中创建浏览器?
- flutter - 在用户点击(平面按钮)上创建一个新的小部件
- javascript - javascript将我所有解密的html列表放入HTML
- python - 将 .txt 网址保存在文件夹中
- docker - Docker 服务以退出代码 0 退出 - Nuls CHAINBOX