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

How To Check If An Object Exists Correctly?

Quick question! Right now I'm using an if statement:

 if game.Workspace.part ~= nil then
	-- Do something
 end

If the part doesn't exist, then I'm getting an error because it is looking for the part to check if it is nil. It works in the sense that the code inside won't run unless the part does exist, but I'd rather have fully functional and optimized code.

So that leads me to my question- what should I be using instead?

2 answers

✓ Accepted answer

do this if you want a child with a specific name:

if workspace:FindFirstChild("Part") then -- use workspace,  game.Workspace is deprecated

end

if you want to find a child that is a part then do this

if workspace:FindFirstChildOfClass("Part") then

end

if you want all the children that are for example a tool or a part then do this:

for i,v in pairs(workspace:GetChildren()) do
if v:IsA("Part") then
-- use v instead of part now
end
end

5 comments

0

Nice! That works perfect, thank you! I'm accepting your answer for the extra effort in different approaches and more detail. Cheers!

0

thanks

0

Um, where does it say game.Workspace is deprecated? It’s the other way around.

0

its all over fourms and the wiki its easier too but you can still use it

0

Link where it says this.

You could:

if workspace:FindFirstChild('part') then
	print('part exists')
end

-- Or

if not workspace:FindFirstChild('Part') then
	print("part doesn't exist :c")
end

Hopefully, this helped, best of luck developer!

Edit: Fixed the string

2 comments

1

You didn't escape the quote on line 8.

0

Thank you very much for the answer! Works exactly like I was hoping.

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