Reputation: 27
So I recently made a Roblox script (in lua) that powers when a button is pressed, it will change the colors of the object I want to change (a light) and it pops up a gui with “code 1” “code 2” etc. every ‘code’ changes the stuff that the light will do. Now, for my problem, I have made only one light, that light works well and stuff, but I want this light everywhere, and every light has to be able to be changed by the script. So I have 1 light, but I want to make dozens of lights and place them everywhere in the facility… is there a way to make a variable of every light, otherwise I will have to make too much variables and lines. If you need a part of the script, the light or the position both are in, tell me. Thanks.
Upvotes: 0
Views: 892
Reputation: 975
A general approach I sometimes take when I need a particular complex model in many different places:
Instead of copying and pasting the model around, I just create simple placeholder parts where I want the models to be. All those parts I put into one folder. Then I have a script that on startup will replace all those placeholder parts with a clone of the model that I want in their place. Here is an example:
Now create the following script in the MyLights folder:
local lightsFolder = script.Parent
for i,v in pairs(lightsFolder:GetChildren()) do
if v:IsA('Part') then
local asset = game.ServerStorage.Assets.Light:clone()
asset:SetPrimaryPartCFrame(v.CFrame)
asset.Name = v.Name
asset.Parent = lightsFolder
v:destroy()
end
end
So upon startup your lights will be placed where ever those parts are. You now only need to modify the looks and behavior of the light in one place. If you don't want them to look all the same, you can define attributes in the placeholder and script them to be applied in the cloning operation. I'll give you an example:
Let's say you want the primary part to be red but only in one of the lights. Select the placeholder part, and in the property editor go to the Attributes section and click "Add Attribute". In the Add Attribute dialog window enter "Color" as Name and "Color3" as Type and click OK. An attribute "Color" has been added. Choose a red color for it.
Now add the following lines into the above script, just before the c:destroy() line:
local color = v:GetAttribute("Color")
if color ~= nil then
asset.PrimaryPart.Color = color
end
You will see that the color you have set in the placeholder's attribute is only applied to the model that is put in its place.
All this is in the spirit of keeping your program DRY.
Upvotes: 1