【问题标题】:How does this script know who 'currentPlayer' is?这个脚本怎么知道'currentPlayer'是谁?
【发布时间】:2021-09-18 16:09:58
【问题描述】:

我是 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 中的“保留名称”,但我在网上找不到任何证据。

【问题讨论】:

    标签: scripting roblox


    【解决方案1】:

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

    在脚本的顶部,您定义了局部变量currentPlayerProximityPrompt.Triggered 信号提供了将其作为函数参数激活的Player 的实例。您也将该参数命名为currentPlayer。在这个函数的作用域中,函数参数隐藏了局部变量,这意味着currentPlayer 引用这个函数参数,而不是你在脚本顶部定义的局部变量。

    为避免这种混淆,将函数参数和局部变量命名为不同的名称通常是一种好习惯。

    如果您希望currentPlayer 引用与 ProximityPrompt 交互的播放器,请尝试将函数参数分配给局部变量:

    prompt.Triggered:Connect(function(player)
        currentPlayer = player
        local char = currentPlayer.Character
        seat:Sit(char.Humanoid)
        prompt.Enabled = false
        print("Character is sitting")
    end)
    

    这将允许您以后的函数保留对 Player 对象的引用。

    【讨论】:

    • 感谢您的帮助 - 我还有一些问题。所以实际的播放器没有在事件处理程序之外实例化?我们将 currentPlayer 定义为 nil,以便我们可以在 Triggered 事件处理函数范围之外使用该变量,如您在示例中所示?是否所有玩家交互都通过 Player 等服务进行管理和传递以连接块,如果是,是否在 API 中定义?再次感谢您的时间和指导。
    • 玩家一加入服务器就被创建/实例化。 Players 服务让您可以通过 Players.PlayerAdded 事件观察这种情况。玩家一直存在,直到该人离开服务器。您不必依赖暴露在对象和服务上的信号来访问这些 Player 对象,您可以将 Player 作为 Players 服务的子对象。这些信号往往是一种相当有效的方法。如果您想了解有关 Roblox API 的更多信息,请查看我在答案中发布的链接,它们会将您带到官方引擎文档。
    • 非常感谢!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多