Atempted to index nil error when trying to find the playergui component of a player

259 Views Asked by At

I'm trying to make a cutscene sorta thing for a dorr in roblox studio. My solution was to set up a collision detector on the door which would then make a gui template and set its parent to the playergui component.

I did this using the code

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)

It tells me: Attempted to index nil with name on line 15.

It works sometimes and sometimes doesnt but recently Ive noticed a trend that I can walk into the door then out again and then it breaks. I haven't coded in a while so I'm a little rusty but I hope I can get some help.

1

There are 1 best solutions below

0
On

You are running into the same issue as this person : Roblox - attempt to index nil with 'leaderstats'

You are not accounting for the fact that the Touched event fires for every single part that touches it, and some of those parts might not belong to a player.

You can protect against this error by making sure that the object belongs to a player before you call 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)