Script For Detecting Changes To All Players

Hello All,

I’m getting a Script error: Script timeout: exhausted allowed execution time
I’m not sure why…(obviously because my scripting is wrong)

Within ServerScriptService is the Script. The purpose of the Script is to get all the Players, then detect if certain Player values change during gameplay, for all the Players. These are value changes such as the number of items collected.

Here’s the Script for your consideration:

local players = game:GetService("Players")

while true do
	for i, player in ipairs(players:GetChildren()) do  --This is the error line
		
		if player["Bunnies Bounced"].Value >= 100 and player["Bunnies Bounced"].Value < 200 then
			player.Mission1 = 1
		end
		if player.Egg.Value >= 100 and player.Egg.Value < 200 then
			player.Mission2 = 1
		end
		if player["Gold Eggs"].Value >= 10 and player["Gold Eggs"].Value < 25 then
			player.Mission3 = 1
		end
		
		wait(.1)
	end
end

I’m trying to keep this detection on the server side and not involve a LocalScript, to minimize potential hacking.
Is there a simple correction for this or is there another approach that I should take to get the same desired outcome?

AVOID using a while function for this. Use Events.

player["Bunnies Bounce"].Changed:Connect (function()
   --- insert here what to do when "Bunnies Bounce" changes
end)

More on this here: Events | Roblox Creator Documentation

That’s a good point. I’ll incorporate that. Any idea for the error line?

Basically there’s a set limit for how long a function can run, and you exceeded it. There is a way to modify this in the Studio settings, but you almost never should do this. Use events and other non-constant running methods wherever possible.

Gottcha.

Your suggestion will work for one player. How can I modify the script so that it loops through all Players in the game and looks for the change?

So assuming you create the valueObjects when a player joins, just connect them to the valueObjects upon creation.

game.Players.PlayerAdded:Connect (function(player)
   local playerMoney = Instance.new("IntValue", player)
   playerMoney.Name = "Money"

   playerMoney.Changed:Connect( function()
      print (player.Name.."'s money was changed!")
   end)
end)

There are events for almost all instances, thus why I recommend you use events for everything possible.

That looks like a good possibility. I’ll give it a try.

As a final note, review this video to learn more about Events. I skimmed through it but it couldn’t be any more thorough on everything events.

Hope this helps!