我在Roblox Lua脚本中遇到问题。我想编写脚本,以免存亡。有小费吗?

时间:2018-07-15 22:43:04

标签: lua roblox

我想编写一个脚本,以便当玩家死亡时,库存中的东西不会消失。这是我当前的脚本,有关如何完成此操作的任何指针或技巧?我已经将其写为本地脚本和服务器脚本,并且在工作区中,但还是没有运气

local Inventory = {}

local function Spawned(Char)
    local Plr = game.Players:GetPlayerFromCharacter(Char)
    for i,v in pairs(Inventory[Plr]) do
        if Plr['Backpack']:findFirstChild(v.Name) then
            Plr['Backpack'][v.Name]:Destroy()
        end
        v.Parent = Plr['Backpack']  
    end
    Inventory[Plr] = {}
    Char:WaitForChild('Humanoid').Died:connect(function()
        for i,v in pairs({Plr['Backpack'], Char}) do
            for ii,vv in pairs(v:GetChildren()) do
                if vv:IsA('Tool') then
                    table.insert(Inventory[Plr], vv:Clone())
                     vv:Destroy()
                end
            end
         end
     end)
 end

game.Players.PlayerAdded:connect(function(Plr)
    Inventory[Plr] = {}
    local Char = Plr.Character or Plr.CharacterAdded:wait()
    Spawned(Char)
    Plr.CharacterAdded:connect(Spawned)
end)

2 个答案:

答案 0 :(得分:1)

将要保留的物品放置在Player.StarterGear中

答案 1 :(得分:1)

可以使用两种不同的方式来存储玩家库存。我将在下面显示几个,以便您可以看到它们。

1。在StarterGear中存储武器

正如牛顿坐标所说,一旦玩家购买武器而不是仅将其放置在背包中,您还可以将其放入.StarterGear文件夹中,这意味着他们每次生成工具时,都会自动将其放置在新背包中。这非常简单,因为您只需要将武器克隆到:

game.Players.LocalPlayer.StarterGear

以及球员背包。您在评论中提到您已经尝试过此操作,但是它没有用,但恐怕我想不出它无法使用的原因。

2。将IntValue用作全局变量

如果无法使用,则另一种方法是每次购买武器时创建一个新的IntValue实例,并在移除武器时销毁它。如果您将IntValue命名为玩家拥有的武器的名称,则可以使用该代码进行编码,以在复制存储中找到该武器(如果存储在其中)。

例如,以下代码(如果放在本地脚本中)将创建一个文件夹来存储IntValue,然后,每当玩家重生代码时,代码便会遍历所有这些IntValue,以获取名称并将相应的武器放入其中。玩家背包。

game.Players.LocalPlayer.CharacterAdded:Connect(function()
    local Children = Storage:GetChildren()
    if #Children > 0 then --If there are stored weapons
        for _, child in pairs(Children) do
            -- Below: Clone the weapon from Replicated Storage using the name from the IntValue
            local WeaponClone = game.ReplicatedStorage:FindFirstChild(tostring(child.Name)):Clone()
            WeaponClone.Parent = game.Players.LocalPlayer.Backpack
        end
    end
end)

local Storage = Instance.new("Folder") --Folder to store current weapons in
Storage.Name = "BoughtWeapons"
Storage.Parent = game.Player.LocalPlayer

我还制作了两个函数,可以调用它们分别创建和销毁IntValue。

local function WeaponBought(WeaponName)
    local WeaponSave = Instance.new("IntValue")
    WeaponSave.Name = WeaponName
    WeaponSave.Parent = game.Players.LocalPlayer.BoughtWeapons
end

local function WeaponRemoved(WeaponName)
    game.Players.LocalPlayer.BoughtWeapons:FindFirstChild(WeaponName):Destroy()
end

您可以将这两个函数放在任何本地脚本中,而不必与其他主要代码一起使用。您需要做的就是将玩家拥有的武器的名称传递给该功能,例如:

WeaponBought("GravityCoil")

这将在文件夹内创建一个名称为“ GravityCoil”的IntValue,供玩家重生时使用。这不像简单地使用StarterGear文件夹那样方便,但是如果由于某种原因您不能这样做,那么这是个不错的选择。

此解决方案的一个小问题是,它将要求将武器存储在复制的存储中,这样开发人员就可以很容易地获得武器而不必购买武器。不幸的是,这只是使用本地脚本执行此操作所带来的问题。

您的代码

我很确定您的代码无法按预期运行的原因是,据我所知,在《 Humanoid》时玩家的背包已经被清理干净了。以获得玩家拥有的武器清单。

我希望这对您尝试做的事情有所帮助,即使这与您要求的不完全一样。