There are plenty of Variants you can do, 2 of the best ones are shown from @StraightScared and @Mystxry12
You Should generally use task.spawn()
or task.defer()
task.spawn()
makes it so code runs immediately, while task.defer()
will take time until the next resumption cycle (To put it simply: Doesn’t run immediately)
While coroutines
yes they are an option, they are generally used for other purposes as task.spawn()
and task.defer()
are used to fire code, and prevent yielding, coroutines
give you more for thread to use and Manipulate the thread but its unlikely you’ll need all this functionality so its best to stick which task.spawn()
for this purpose
If you ever want to keep track of all the Light Holding Instances (or the Lights themselves), you should use CollectionService
instead of looping through the Descendants of something, it would put less on the Server as it already has a specified list of objects with CollectionService:GetTagged()
, while yes, :GetDescendants()
works, its slower as it has to loop through children, and then their children, and then their children, which can take a while, so it would be best to have a already made list, or a list to Apply when doing such things, to Add an Instance to a Tag, you would use AddTag
and to remove, its RemoveTag
.
@zahra_y735
Instead of checking if all of these items are from a certain class, just use the Class: Light
Which is a shared class for all Lighting Related Instance, Lights can refer to, it could make your code look nicer and making the Server not have to look through so many classes, when it can all be specified in one,
if val:IsA("Light") then
-- code
end
If you are looking for a specific class, then it is recommended to do this for a specific class, not all, It is recommended you use Instance:IsA()
instead of Instance.ClassName ==
, :IsA()
already does this for you by check if the Instance
Is a certain class, Instance.ClassName
is just overcomplicating things.
If you are looking for an Ordered Sequence, you should have a Table of these Sequences, and loop through the index keys.
LightSeq = {1, .5, .1} -- List of Numbers for use to use
index = 0
while true do
index = (index % #LightSeq) + 1 -- to prevent the index from being 0
Light.Brightness = LightSeq[index]
task.wait(.5)
end
Small Rant on Math
The math is using what is known as Modulo %
, it is used to get the remainder of Division, but here, it has a very good use, when we use it for numbers, if we have a number 3
, and 5
, we can do 3 % 5
which returns 3
, but when we do 5 % 5
, it returns 0
, 6 % 5
is 1
and the process repeats itself, it effectively removes the usage of an if statement to check if a number is greater than a number to reset it.
If you want a Random Sequence of said Numbers:
LightSeq = {1, .5, .1}
Light.Brightness = LightSeq[math.random(1, #LightSeq)] -- Randomized Sequence