【问题标题】:Attempt to index nil尝试索引 nil
【发布时间】:2020-07-08 14:15:36
【问题描述】:

我正在尝试创建取件,但是当您取件时弹出错误消息。 这是错误:

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)

【问题讨论】:

标签: lua roblox


【解决方案1】:

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

不允许索引 nil 值。

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

.Parent
[Parent]
:Parent

然后找到:

humanoid.Parent

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

要么确保 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")

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

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 2021-09-04
    • 2022-01-05
    • 2016-05-09
    • 2021-08-02
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多