如何使Roblox脚本搜索玩家的背包

问题描述 投票:0回答:2

我正在尝试编写一个脚本,当玩家触摸门时,该脚本会搜索玩家的背包,以便它可以判断玩家是否有钥匙卡。如果玩家有钥匙卡,它应该说“是”,但是由于某种原因,它会不断出现错误。这是我的代码:

function onTouched(m)
p = m.Parent:findFirstChild("Humanoid")
if p ~= nil then
        n = p.parent
        local letin = game.Players(n).Backpack:FindFirstChild("Key Card")
        if letin then
        print("Yes")
        else
        print("No")
        end
    end
end

script.Parent.Touched:connect(onTouched)

错误是:

Trying to call method on object of type: 'Player' with incorrect arguments.

有人知道为什么这可能行不通吗?

roblox
2个回答
1
投票

我认为您有两个问题:

  • 似乎您正在尝试访问数组索引,但是您使用的是()而不是[]。

  • game.Players对象是服务类,而不是数组。但是您可以调用game.Players:GetPlayers()来获取该组播放器。

由于已经获得了玩家对象,因此您可以简单地获取玩家的名称,并使用该名称从game.Players中查找玩家。

您的脚本即将运行,这是为您提供的解决方案:

function onTouched(m)

    -- get the player in game that touched the thing
    local p = m.Parent:findFirstChild("Humanoid")
    if p ~= nil then

        -- grab the player's name
        local n = p.parent.Name

        -- find the player in the player list, escape if something goes wrong
        local player = game.Players:FindFirstChild(n, false)
        if player == nil then
            return
        end

        -- search the player's backpack for the keycard
        local keycard = player.Backpack:FindFirstChild("Key Card")
        if keycard then
            print("Yes")
        else
            print("No")
        end
    end
end

script.Parent.Touched:connect(onTouched)

0
投票

以下代码行是不正确的,因为与其在'game.Players',您可以通过括号将其称为函数。

local letin = game.Players(n).Backpack:FindFirstChild("Key Card")

您可能想要的是:

local letin = game.Players[n].Backpack:FindFirstChild("Key Card")

获得“钥匙卡”的更干净的方法是还检查“ n”是否真的是玩家的名字,而不是NPC的名字。

local player = game.Players:FindFirstChild(n)
if player then
   local letin = player.Backpack:FindFirstChild("Key Card")
   print(letin)
end
© www.soinside.com 2019 - 2024. All rights reserved.