Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Is there a way to check if a variable still exists?

local Part = script.Part:Clone()
Part.Parent = workspace    
Debris:AddItem(Part, 10)

while true do
    Part.Transparency = 0.5
    wait(1)
    Part.Transparency = 0
    wait(1)
end

The Debris service would destroy the part after 10 seconds, however, the loop will still run and therefore error as the part no longer exists

while Part do

The code above doesn't seem to fix this, I do not wish to use :FindFirstChild() as there will be multiple parts called "Part" etc.

2 comments

0

if Part then

0

you can use FindFirstChild("Part") because it only looks for the part inside the script

2 answers

I'm not aware of a way to check if a part exists without using FindFirstChild(), but you could increment a variable every loop to check if 10 seconds have passed yet.

local Part = script.Part:Clone()
Part.Parent = workspace

local seconds = 0

game:GetService("Debris"):AddItem(Part, 10)

while true do

	Part.Transparency = 0.5
	wait(1)
	Part.Transparency = 0
	wait(1)
	
	seconds = seconds + 2
	
	if seconds >= 10 then
		break
	end
	
end

To check if an Instance still exists, you would compare it to nil as according to what you are doing:

local part = script.Parent:Clone()
part.Parent = workspace
game:GetService("Debris"):AddItem(part, 10)
while part ~= nil do
	part.Transparency = 0.5
	wait(1)
	part.Transparency = 0
	wait(1)
end

Plus, you have a good point. FindFirstChild() may not work because the parts may have different names. It will return any instance by the given name in the sub-directory that is below where FindFirstChild() is being called from.

This discussion is preserved as it was. New answers, comments, and votes are closed.