Way to optimize this message script?

So, I’ve been working on this script that displays a message on screen when you activate a proximity prompt.
The proximity prompt fires a remote event that actives the local script below.
What is happening is when I start a new message when one is already onscreen, the loop from the message function is staying and causing the new message to end early.
Could someone help with this?
I’ve tried using :Disconnect and other things, but I can’t get it to work.

local text = script.Parent.TextLabel

local sound = script.Parent.sound

local running = false

local re = false

local function typewrite(t, m)
	for i=1, #m, 1 do
		if re == true then
			break
		end
		t.Text = string.sub(m, 1, i)
		wait(0.05)
	end
end

local function message(m)
	
	local se = 1
	re = false
	running = true
	sound:Play()
		text.Visible = true
		text.Text = ""
	--typewrite(text, m)
		text.Text = m
		for i = 20, 0, -1 do -- the part causing the problem btw
			if re == true then
				break
			end
		--print(tostring(re) .. se)
		se = i
		wait(0.1)
		end
	re = false
	text.Visible = false
	text.Text = ""
	running = false
		--[[for i=1, 100 do
			text.TextTransparency = i/100
			wait(0.01)
		end]]--
end

game.ReplicatedStorage.Message.OnClientEvent:Connect(function(m)
	if running == true then
		re = true
		message(m)
	else
		message(m)
	end

end)

Maybe add a BoolValue value to the display then toggle to end last message.
– in a message loop

local toggle = script.Parent.bool
while true do task.wait(1)
	if toggle.Value == true then toggle.Value = false
		-- clear text
		break
	end
end

Triggering it from the start of the next message or ending it.
(this is not a working code … just a possibility)

1 Like

two things you could do, if you only want one message at a time, put a debounce. while a message is running, don’t accept any new requests.

if you want to have messages override it, then have a way to break out of the message function and cease functionality. what i’d recommend is having a log time variable in and out of the function. something like this:

local currentTime = time()

function runMessage(text, message)
   currentTime = time()
   local messageTime = currentTime

   for i = 1, #message, 1 do
		if messageTime < currentTime then
			break
		end

		text.Text = message:Sub(1,i)
		task.wait(0.05)
	end
end

something like that without using true or falses should attempt to stop overlaps

1 Like