首页 > 解决方案 > 这个脚本怎么知道'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 中的“保留名称”,但我在网上找不到任何证据。

标签: scriptingroblox

解决方案


您的脚本将局部变量与函数参数混淆了。

在脚本的顶部,您已经定义了局部变量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 对象的引用。


推荐阅读