尝试对空值进行索引

我正在尝试创建拾取物,但在拾取时出现错误。 错误信息如下:

Workspace.LogPickup.LogPickupScript:8: attempt to index nil with 'Parent'

脚本的第8行是变量player。 以下是代码:

local log = script.Parent
local logGuard = false

local function onTouch(partTouched)

    local character = partTouched.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    local player = game.Players:GetPlayerFromCharacter(humanoid.Parent)
    local playerStats = player:FindFirstChild("leaderstats")
    local playerLogCount = playerStats:FindFirstChild("Has Log")

    if humanoid and logGuard == false then

        log.Transparency = 1
        log.CanCollide = false
        logGuard = true
        playerLogCount.Value = 1

        wait(5)

        log.Transparency = 0
        log.CanCollide = true
        logGuard = false

    end

end

log.Touched:Connect(onTouch)
点赞
用户2858170
用户2858170

这个错误告诉你,在第8行中,使用关键字“Parent”索引了一个空的值。

不允许索引空的值。

在第8行中,搜索以下任何一项:

.Parent
[Parent]
:Parent

并查找:

humanoid.Parent

现在你知道humanoid是一个空值,你不能对它进行索引。

要么确保character:FindFirstChildWhichIsA("Humanoid")总是返回预期的值,要么在索引之前检查它是否已经存在。

local character = partTouched.Parent
local humanoid = character and character:FindFirstChildWhichIsA("Humanoid")
local player = humanoid and game.Players:GetPlayerFromCharacter(humanoid.Parent)
local playerStats = player and player:FindFirstChild("leaderstats")
local playerLogCount = playerStats and playerStats:FindFirstChild("Has Log")

短路是避免索引错误的一个简单方法,只要你能确保你得到的是空值或者预期的值。

2020-07-08 06:15:36