尝试索引空值错误,当试图找到 Roblox 中玩家的 PlayerGui 组件时

我正在尝试为 Roblox Studio 中的门制作一个类似于过场动画的东西。我的解决方案是在门上设置一个碰撞检测器,然后制作一个 GUI 模板,并将其父级设置为玩家的 PlayerGui 组件。

我使用以下代码来实现这一点

local afterIntoTransform = script.Parent.Parent.DoorUnion.Position.Z -6
local afterOutwardsTransform = script.Parent.Parent.DoorUnion.Position.Z + 6
local debounce = false

local function executeFadeSceneAndTpPlayer(player)
    local fadeScene = Instance.new("ScreenGui")
    local fadeSceneFrame = Instance.new("Frame")
    fadeScene.Name = "fadeScene"
    fadeSceneFrame.Name = "fadeFrame"
    fadeSceneFrame.Size = UDim2.new(1,0,1,0)
    fadeSceneFrame.Parent = fadeScene
    fadeSceneFrame.BorderSizePixel = 0
    fadeSceneFrame.BackgroundColor3 = Color3.new(1, 1, 1)
    fadeSceneFrame.BackgroundTransparency = 1
    print(game.Players:GetPlayerFromCharacter(player).Name)
    fadeScene.Parent = game.Players:GetPlayerFromCharacter(player).PlayerGui
    for i = 0, 20, 1 do
        fadeSceneFrame.BackgroundTransparency -= 0.05
        wait(0.01)
    end
    player.HumanoidRootPart.Position = Vector3.new(player.HumanoidRootPart.Position.X, player.HumanoidRootPart.Position.Y, afterOutwardsTransform)
    for i = 0, 20, 1 do
        fadeSceneFrame.BackgroundTransparency += 0.05
        wait(0.01)
    end
    fadeScene:Destroy()
end

script.Parent.Touched:Connect(function(hit)
    if not debounce then
        debounce = true
        executeFadeSceneAndTpPlayer(hit.Parent)
        wait(0.2)
        debounce = false
    end
end)

它告诉我: 尝试索引空值错误,在第 15 行上。

它有时候有效,有时候无效,但最近我注意到一个趋势,就是我可以走进门,然后再走出来,然后它就会出问题。我已经有一段时间没有编程了,所以有点生疏,但我希望能得到一些帮助。

点赞
用户2860267
用户2860267

你遇到了和这个人一样的问题:Roblox - attempt to index nil with 'leaderstats'

你没有考虑到Touched事件会针对每个碰触到的部件触发,而其中一些部件可能不属于玩家。

为了避免这个错误,你可以在调用executeFadeSceneAndTpPlayer()之前确保对象属于一个玩家。

script.Parent.Touched:Connect(function(hit)
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    if not plr then
        return
    end

    if not debounce then
        debounce = true
        executeFadeSceneAndTpPlayer(hit.Parent)
        wait(0.2)
        debounce = false
    end
end)
2020-09-29 21:16:27