Help with an error that happens 50% of the time

With my previous topic, I was getting help with my mirror / webcam thing made from a viewport frame.
and now I need help with having it work 100% of the time

sometimes when launching a playtest / playing the game, this error happens

Players.BallOTinfoil.PlayerGui.SurfaceGui.the player copy and cframe one:3: attempt to index nil with 'Parent'  -  Client - the player copy and cframe one:3

basically meaning it can’t find the surface gui adornee’s parent… (on line 3)
I have no idea how to begin to fix this as i’ve already separated the error into variables to find the error and I don’t know how to wait until it finds the parent
(kinda thinking like WaitForChild but instead for the parent)

anyways, I need help with this
ty for all the help!
(script below):

local gui = script.Parent
local Adornee = gui.Adornee
local AdorneeParent = Adornee.Parent

local ViewportCamera = Instance.new("Camera")
ViewportCamera.CFrame = AdorneeParent.CameraDirection.CFrame
ViewportCamera.FieldOfView = 70
gui.ViewportFrame.CurrentCamera = ViewportCamera

local RunService = game:GetService("RunService")

local DetectZone:BasePart = gui.Adornee.Parent.Detection


RunService.Heartbeat:Connect(function(step)
	gui.ViewportFrame.WorldModel:ClearAllChildren()
	for _,player in game.Players:GetPlayers() do
		for _,part in player.Character:GetChildren() do
			local clone = part:Clone()
			clone.Parent = gui.ViewportFrame.WorldModel
		end
	end
end)

You could for example use the following code snippet to wait for the adornee to be set:

while not gui.Adornee do
	task.wait()
end
local Adornee = gui.Adornee

It waits until the property Adornee isn’t nil
The error is caused since the code is trying to index the variable Adornee with .parent but the adornee didn’t exists at the time of assigning the variable so it became nil

3 Likes

Thank you so much! it seems to work every time now!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.