【问题标题】:How to make a Roblox script search a player's backpack如何让 Roblox 脚本搜索玩家的背包
【发布时间】:2019-06-27 10:57:54
【问题描述】:

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

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.

有谁知道为什么这可能不起作用?

【问题讨论】:

  • 错误是什么?
  • 它说:试图调用类型对象的方法:'Player' 参数不正确。

标签: roblox


【解决方案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)

【讨论】:

    【解决方案2】:

    下面这行代码不正确,因为不是在 '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
    

    【讨论】:

      猜你喜欢
      • 2015-05-17
      • 2019-01-10
      • 2022-06-21
      • 2022-10-05
      • 2018-12-16
      • 2021-06-16
      • 2022-10-24
      • 2019-06-26
      • 2015-07-10
      相关资源
      最近更新 更多