Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How To Check If An Object Exists Correctly?

Asked by 6 years ago
Edited 6 years ago

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

Log in to vote
-2
Answered by 6 years ago

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
0
Nice! That works perfect, thank you! I'm accepting your answer for the extra effort in different approaches and more detail. Cheers! pick1ehead 53 — 6y
0
thanks mattchew1010 396 — 6y
0
Um, where does it say game.Workspace is deprecated? It’s the other way around. User#19524 175 — 6y
0
its all over fourms and the wiki its easier too but you can still use it mattchew1010 396 — 6y
0
Link where it says this. User#19524 175 — 6y
Ad
Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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

1
You didn't escape the quote on line 8. oreoollie 649 — 6y
0
Thank you very much for the answer! Works exactly like I was hoping. pick1ehead 53 — 6y

Answer this question