I have a system where I find myself assigning variables to a bunch of parts. This appears to be unavoidable, as I need to manage the properties of each individual part in a lighting pattern.
Is there a way I could loop through a model and assign a new variable to each part based on its name?
Iāve thought about using this, yes. What Iām specifically looking for is if I can assign a variable to a partās name for a group of parts.
(psuedocode)
local groupOfParts = {}
for i, v in pairs(workspace.Lights:GetChildren()) do
print(v.Name)
end
-- V1
-- V2
for i = 1, #groupOfParts do
variable = groupOfParts[i]
end
print(V1) -- workspace.Model.V1
print(V2) -- workspace.Model.V2
print(V3) -- nil
Otherwise, I believe there are multiple ways to construct a table to meet your needs. OssieNoMae suggested one above and here is a suggestion that I think is more in line with your requirements:
The downside to the above solution would be the time spent searching through the table and finding the subtable containing the part you want. This would require two for loops unfortunately.
Though you canāt assign a variable directly to your script through your own script at runtime, you can use tables and instead assign keys inside it with your modelās child as the value as such:
local model = workspace.MyModel
local a = {}
for _, child in pairs(model:GetChildren()) do
if child:IsA("BasePart") then
a[child.Name] = child
end
end
--[[
Let us assume there were parts named "Part1", "Part2" and "Part3" in the model
now you can do things like this:
]]
a.Part1.Transparency = 1
print(model.Part1.Transparency) --> 1
This isnāt truly a direct variable but hey, itās just two characters a. more ĀÆ\_(ć)_/ĀÆ