Hello! I've been working on a little side project recently and have run into a recurring problem; infinite loops. Here is an example of one of these problems:
x = true wait(4) player = game.Workspace:FindFirstChild("Juolite") while x do if (script.Parent.Position - player.HumanoidRootPart.Position).Magnitude <= 40 then script.Parent.PointTwo.Transparency = 0 else script.Parent.PointTwo.Transparency = 1 end wait(0.2) end
In the code above, I've got a little part (PointTwo) that appears when a player is within a certain radius of the script's Parent part (40 studs). I've just been learning how .Magnitude works. The code runs fine. The problem is, I'd like to avoid using an infinite loop here, and in future scripts too. How should I go about doing this?
Well if you're looking to decrease lag I've got you since I'm mostly into this stuff.
So you have a couple options here:
- Put the loop on the client and check on the client.
Loops on clients are definitely better then putting them on the server. You can check for statements and such on the Client and then send a signal to the server after.
- You can use .Changed
.Changed
is a common event normally used on Value instances such as IntValue
or ObjectValue
or StringValue
.
- You can use GetPropertyChangedSignal on the velocity of root part
GetSignalPropertyChanged is an event that will run when a specific property is changed. If the character is moving
then the velocity wouldn't be 0, 0, 0,
If they are moving one of these values will change. You can detect if the velocity are certain values and then run checks so that only when the character is moving you check.
- You can use GetPropertyChangedSignal on Position or CFrame
I'd personally wouldn't do this as it's unnecessary but it's basically number 3 but with orientation
- RunService
A lot of people use RunService mostly for the client. It does act like a loop.
So, I personally would do the Velocity or Position / CFrame one as it is the most reasonable ones.
Hope this helped if you have any questions feel free to contact me via comments
To be honest if it’s nesscary to have an infinite loop then go for it. Limit the un nesscary amount of loops. I don’t think this would lag up the game since if the loops execute at the same time with using a wait(0.2) since the scripts in a character already do that.
For your script I’m not sure if there is a Walk Event for the humanoid. If there is then make a debounce for sure to make sure the event only runs once every 0.2 seconds. Then do your distance thing and you have just avoided using a infinite loop!
Just make sure whenever you don’t need the event anymore you disconnect it.
If you need clarification ask me anytime.