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

How to use variables to refer to an instance?

Asked by 4 years ago
Edited 4 years ago

This is a test script:

wchildren = game.Workspace:GetChildren()
for a, b in ipairs(wchildren) do
    game.Workspace.b:Destroy()
end

However, the game seems to be looking for an object named b instead of one with the name of the variable b.

b is not a valid member of Workspace

Edited: changed code

0
The problem is that b itself is the instance you are looking for. Try print(b.Name) instead and you'll see what I mean. For better coding practices do local wchildren = workspace:GetChildren(). msuperson24 69 — 4y
0
workspace:GetChildren() creates a table of all instances that descend from workspace, and the loop you are using enumerates the items in the table with i, and assigns the item to b. msuperson24 69 — 4y

1 answer

Log in to vote
1
Answered by
JesseSong 3916 Moderation Voter Community Moderator
4 years ago
Edited 3 years ago

Problem:

You can't do game.Workspace.b:Destory()

The reason being is that if you do it, the script will think you're trying to delete b, which in this case doesn't exist and will hence an error!

Solution:

If you want to delete "B" then make sure you use b.Name or something so that the script will not get confused.

If you want to delete everything in the workspace then type the following code:

wchildren = game.Workspace:GetChildren() -- Gets the children of the workspace
for a, b in ipairs(wchildren) do
    b:Destroy() -- destroys everthing in the workspace
print "The item has been destroyed!"
end

If this helped you, please accept!

0
Yes, this works. I figured out that GetChlidren was making a table of userdata, not strings. bomblitz06 94 — 4y
0
Fixed a minor grammatical error - January 31, 2021 JesseSong 3916 — 3y
Ad

Answer this question