尝试索引 nil

Attempt to index nil

我正在尝试创建取件,但取件时出现错误。 这是错误:

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)

此错误告诉您在第 8 行中使用键 'Parent' 索引了一个 nil 值。

不允许索引 nil 值。

在第 8 行中搜索以下任一内容:

.Parent
[Parent]
:Parent

并找到:

humanoid.Parent

现在你知道 humanoid 是一个你不能索引的 nil 值。

要么确保 character:FindFirstChildWhichIsA("Humanoid") 总是 returns 预期值,要么在索引它之前检查它是否确实如此。

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")

短路是一种避免索引错误的简单方法,只要您可以确定得到的是 nil 或预期值即可。