尝试将对象克隆到背包时得到零响应

Getting a nil response while trying to clone a object to backpack

我正在尝试在触摸对象部分时将对象从复制存储克隆到玩家背包,并且代码对我来说看起来不错,但它一直给出来自 clone.parent = player.backpack

的零响应
local replicatedtorage = game:GetService("ReplicatedStorage")
local Sword = replicatedtorage:FindFirstChild("Sword")

local part =  game.Workspace.Part

local player = game.Players.LocalPlayer
local clone = Sword:Clone()

part.Touched:Connect(function(hit)
    local humanoid = hit.parent:FindFirstChild("Humanoid")
if humanoid ~= nil then
    clone.Parent = player.Backpack
end
end)

这看起来像服务器 Script,它无法像客户端那样访问 Players.LocalPlayer,因为服务器没有本地播放器。获得触及零件的 Player 的一种方法是通过 Players:GetPlayerFromCharacter(),这需要传递一个实例,并且 return 其角色为该实例的 Playernil.

part.Touched:Connect(function(hit)
    local character = hit.Parent
    local player = game.Players:GetPlayerFromCharacter(character)
    if player then
        clone.Parent = player.Backpack
    end
end)

这应该会立即在您的脚本中运行,并且可以替换您现有的 Touched 连接。