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:
1 | local ObjectName = "TestObject" |
3 | if game.ServerStorage [ ObjectName ] then |
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()
1 | local ObjectName = "TestObject" |
3 | if game.ServerStorage:FindFirstChild(ObjectName) then |
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:
1 | local SecondaryName = v.Weapons.Secondary.Text |
2 | local Secondary = game.ServerStorage.Weapons.Secondary:FindFirstChild(SecondaryName) |
5 | local SecondaryClone = Secondary:Clone() |
6 | SecondaryClone.Parent = v.Backpack |
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.