Better alternatives or optimizations to my script

Hello! I am wondering if there are any alternatives that are better than my script or any optimizations that I can do on my script.

    local finished_talking = false
	
	-- ignore this
	game.ReplicatedStorage.say_dialogue:FireClient(player, "start")
	
	-- when the event is fired to server, then that means
	-- the player is done talking
	game.ReplicatedStorage.finished_dialogue.OnServerEvent:Connect(function()
		finished_talking = true
	end)
	
	-- yielding the script until it has received that event
	while true do
		if finished_talking then break end
		
		game:GetService("RunService").Heartbeat:Wait()
	end

I heard constantly yielding was bad for a script so what can I do better?

You’re constantly polling in a while loop which is inefficient, instead use :Wait() on finished_diagloue which yields the current thread until it fires, that way, you’re only adding 1 task to the task scheduler, don’t constantly poll for no reason as it is inefficient and unnecessary and can overload the task scheduler.

Also, it’s better to define ReplicatedStorage in a variable so you don’t have to index it every time.

local ReplicatedStorage = game:GetService("ReplicatedStorage")

ReplicatedStorage.say_dialogue:FireClient(player, "start")
	
-- when the event is fired to server, then that means the player is done talking, 
ReplicatedStorage.finished_dialogue.OnServerEvent:Wait()
2 Likes

cool, i will be trying what you said. thanks for the advice!

Try putting the rest of your delayed code in the event itself, :Wait() only works for the amount of times you call it. If that’s what you’re looking for then you don’t have to do anything else.