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

How to change an object using a variable for a part of the name?

Ok so, this might seem a little confusing. Basically, there are 20 objects named "confirm" and then a number. There are 20 so they are all numbered from 1 to 20. Example. Workspace.confirm1, workspace.confirm2... ext.

So, I want to delete one based on a value that is set a number between 1 and 20 randomly.

And I want to delete the confirm object with that number without handwriting every single one.

Example.

If workspace.Value.Value == 1 then
workspace.confirm1:Destroy()
Elseif workspace.Value.Value == 2 then
workspace.confirm2:Destroy()
End

Instead, I wanted to makebit easier, so I used brackets, brackets should have worked, but didn't. I wrote this

workspace.confirm[workspace.Value.Value]:Destroy()

But the output said it couldn't find the object "confirm", so obviously, that means it didn't add what was in the brackets, instead it only looked for something named "confirm", how do I make the variable (the value in the brackets) work and add it to the name of the object I want to Destroy?

2 answers

✓ Accepted answer

Your being to complicated, it's not necessary. All you need to do is change where the brackets are.

You are correct and you can use brackets for variables, but they are in the weokng place.

It's kind of like when you print something, if u use a variable, you type

Print("info:"..variable)

So do the same with ur code.

If you type this it should work

Workspace["confirm"..value]:Destroy()

1 comment

0

OMG thank you so much. Finally It works

Quite simple. You can do some cool string.concat stuff in order to do this.

local number = tostring(game.Workspace.Value.Value) 
local concat = "confirm"..number
local todestroy = game.Workspace:FindFirstChild(concat)

This should work. If it doesn't, leave a comment and I'll fix the mistake.

2 comments

1

I'm not saying FindFirstChild is bad, but if we know for a fact that the object exists then we might as well use square brackets (for example, game.Workspace[concat]). It's more concise and I find it improves readability. Good answer.

0

Ur stupid

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