首页 > 解决方案 > 尝试查找玩家的 playergui 组件时尝试索引 nil 错误

问题描述

我正在尝试为 roblox 工作室的 dorr 制作一个过场动画。我的解决方案是在门上设置一个碰撞检测器,然后制作一个 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 行用名称索引 nil。

它有时有效,有时无效,但最近我注意到一种趋势,即我可以走进门然后再出去,然后它就坏了。我有一段时间没有编码,所以我有点生疏,但我希望能得到一些帮助。

标签: luaroblox

解决方案


您遇到了与此人相同的问题:Roblox - 尝试使用 'leaderstats' 索引 nil

您没有考虑到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)

推荐阅读