Something like .Changed waits until some property of an object changes, then triggers a function when said property changes…
but isn’t that just a loop? It’s constantly checking whether an attribute of an object has changed. How is it different than using a while loop, repeat loop, or runservice?
Well technically, you can consider a .Changed to be a loop since the client or server is constantly checking the properties of said thing. You can also think of it as the changed property firing an event to the script or script’s that has this detector in them.
But the reason for having a .Changed is to make sure it doesn’t fire endlessly once said properties change. So basically a loop with its own switch.
Also when using a while wait() do loop, any triggers going after the loop will not fire since the script goes through the instructions top to bottom, and it gets stuck on the while wait() do loop. Of course if there is a .Changed event after the loop, then it’ll work just fine.
For example:
while wait() do
script.Parent.NumberValue = script.Parent.NumberValue + 1
end
script.Parent.NumberValue.Changed:Connect(function()
print(script.Parent.NumberValue.Value)
end)
-- This works just fine, since the .Changed is only going to fire if said event happens:
----------------------------------------------------------------------------------|
while wait() do
script.Parent.NumberValue = script.Parent.NumberValue + 1
end
function Counter()
print(script.Parent.NumberValue.Value)
end
Counter()
-- This will not work, since the script is now stuck on the while wait() do loop, it cannot fire any event's by itself after the loop. However it will work if it's before the loop
I also feel like it just takes less resource’s from your computer or server. Especially when you consider that if you accidentally forget to put a wait() in the while do loop, it will cause a timeout error, or even crash the game. So .Changed just seems to be a Anti-Timeout/Anti-Crash form and mostly more convenient option for scripting.
Let’s say we have a button: The benefit of the event pattern is that there’s no cost until the button is actually clicked. The event can be handled this way without being monitored because it originates from what we call a “hardware interrupt,” which briefly preempts the running code to fire the event.
Some UI and game frameworks use something called a “message loop,” which queues events for execution at some later (usually short) time period, but you still need a hardware interrupt to get that event into the message loop in the first place.
Everything else you ever need to know about this will be listed below.
The way that .Changed (which, just use :GetPropertyChangedSignal, it’s much better) at least should work is that when someone / something sets a property, it will fire that event. It doesn’t check the property every time and then check if it changed, instead when that property is set, it fires that event. If it’s the same value as before, it doesn’t fire it.