Why is this script choosing a random number constantly when I have told it to wait 20 seconds?

I have scripted a wait(20) at the start of the while loop because I want the script to choose an animation every 20 seconds. However, it decides to choose a random number constantly and tries to do every animation at the same time.

    --//Main\\--

beast.Parent.Changed:Connect(function()
		
		while humanoid.Health > 0 do
			wait(20)
			local animationChance = math.random(1, 4)
			print("Animation chance = "..animationChance)
			
			if animationChance == 1 then
				swingLeft()
				
	
				
				
			elseif animationChance == 2 then
				swingRight()
				
				
				
				
			elseif animationChance == 3 then
				slam()
				
		
				
				
			elseif animationChance == 4 then
				scream()
				
				
				
		
			end
			
		
			end
			
			end)

Every time beast’s Parent’s properties change in any way, a loop is started that does this stuff until the character dies. So it is possible for multiple of these loops to be running at once, which is probably not what you want.

3 Likes

I put an if statement after the parent is changed so that it only runs if it’s in workspace. Would that work?

No, that’s fairly unrelated.

I’d say replace your “Connect” line with the following and you might get your intended behavior.

spawn(function()
-- rest of the code...
end)
2 Likes

There’s no need to create a coroutine in this case though. As mentioned above, it’s because multiple loops are being created whenever the parent changes. If this resolved the issue it’s because that signal has been removed

The idea is that you spawn one thread asynchronously rather than one on each invoke of the signal. You could also not wrap it in a spawn, but then you’re assuming there’s no code after the original code that OP posted, which may not be the case. Currently marked solution is safest answer.

Yeah, I’m talking about removing the signal entirely. There’s no point wasting a thread if it’s not needed. I didn’t realise this was only a segment of the script (if it is)

Just for further notice, Connections are created each time the method is called; no existing connections replaced or overwritten. Similarly, you could create functions and fill a call table up with those functions and the same concept will occur. If you wish to wait for a signal to fire, use :Wait(), otherwise use the above methods or just structure your code better / remember what is connected and what to disconnect.

I figured he’s got more he’s not sharing, so went with spawn instead of a while loop.