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

Check if searched object exists?

Asked by 4 years ago

I'm looking to see if a tool is in ServerStorage that a player has entered in their textbox.

Here is an example of what I attemped:

                    local SecondaryName = v.Weapons.Secondary.Text
                    if not game.ServerStorage.Weapons.Secondary[SecondaryName] then

                    else

                    local Secondary = game.ServerStorage.Weapons.Secondary[SecondaryName]:Clone()
                    Secondary.Parent = v.Backpack

The game stops after the "if not" when the object doesn't exist. This is what I'm trying to prevent by using the statement. What else could I try?

I know you can use this to see if parts or objects exist and I can partially see why this wouldn't work but not sure what else to use.

Extra: The text is sent to this Server Script from a remote function so this is all server-side

0
sorry, i suppose i could have explained this in my answer to your last question Gey4Jesus69 2705 — 4y

1 answer

Log in to vote
2
Answered by 4 years ago

The problem here is that, by using brackets, you are implying that the object you're looking for actually exists. What happens if it doesn't? The same thing that would happen if I tried to say workspace.PartThatDoesNotExist:Destroy(). It will error. Thus, we have to work around this.

Thankfully, we can use :FindFirstChild() to do this. Take this snippet, for example, which does not use the method:

local ObjectName = "TestObject"

if game.ServerStorage[ObjectName] then
    print("Found!")
end

The problem here is that this snippet will error if the object does not exist, despite the fact that we ran this if statement. To satisfy the error, we can simply use :FindFirstChild()

local ObjectName = "TestObject"

if game.ServerStorage:FindFirstChild(ObjectName) then
    print("Found!")
end

Now, if the given object exists, it will be found. If it doesn't, though, we don't have to worry.


In your case, then, all we have to do is add this method to prevent any errors:

local SecondaryName = v.Weapons.Secondary.Text
local Secondary = game.ServerStorage.Weapons.Secondary:FindFirstChild(SecondaryName)

if Secondary then
    local SecondaryClone = Secondary:Clone()
    SecondaryClone.Parent = v.Backpack
end

As a note, I know people probably dislike the amount of variables I used in that last code snippet. I could have simply said Secondary:Clone().Parent = v.Backpack. I don't like doing this in most situations, though, because then I lose control over the cloned object, so I can't make changes to it later.

1
Works great! Darksniper600 104 — 4y
Ad

Answer this question