How do I replace the current running function with a new one

I am trying to make a system that explains the story to the player using a slideshow, but two text functions are overlapping and causing issues. How can I stop the current function and start the new one to prevent overlap?

-- Function
local function Text()
	for i=1, #text do
		script.Parent.TextLabel.Text = string.sub(text,1,i)
		coroutine.wrap(soundPlay)()
		
		wait(0.04)
	end
end

-- Next Slide
script.Parent.Forward.MouseButton1Click:Connect(function()
	CurrentSlide += 1
	script.Parent.Back.Visible = true
	if CurrentSlide == 5 then
		humanoid.WalkSpeed = 16
		player.CameraMode = Enum.CameraMode.LockFirstPerson
		script.Parent.Parent.Visible = false
		Events.GameStarted:FireServer()
	end
	script.Parent.StoryImage.Image = SlideImages[CurrentSlide]
	text = SlideTexts[CurrentSlide]
	Text()
end)

I have tried looking for a possible solution, but none have worked and I don’t know how I can fix this issue.

no way it’ll work i havent tested it

-- Function
local TweenService = game:GetService("TweenService")

local LastTextTween = nil

local function Text()
	if LastTextTween then
		LastTextTween.Tween:Pause()
		LastTextTween.Value:Destroy()
	end
	
	local NewSub = Instance.new("NumberValue")
	NewSub.Value = 1
	
	local Tween = TweenService:Create(NewSub, TweenInfo.new(0.04 * string.len(text)), {["Value"] = string.len(text)})
	local LastNum = 0
	
	NewSub:GetPropertyChangedSignal("Value"):Connect(function()
		if math.round(NewSub.Value) ~= LastNum then
			script.Parent.TextLabel.Text = string.sub(text, 1, NewSub.Value)
			coroutine.wrap(soundPlay)()
			
			LastNum = math.round(NewSub.Value)
		end
	end)
	
	LastTextTween = {Tween = Tween, Value = NewSub}
	
	Tween:Play()
	
	Tween.Completed:Once(function()
		NewSub:Destroy()
		Tween:Destroy()
		LastTextTween = nil
	end)
end

-- Next Slide
script.Parent.Forward.MouseButton1Click:Connect(function()
	CurrentSlide += 1
	script.Parent.Back.Visible = true
	if CurrentSlide == 5 then
		humanoid.WalkSpeed = 16
		player.CameraMode = Enum.CameraMode.LockFirstPerson
		script.Parent.Parent.Visible = false
		Events.GameStarted:FireServer()
	end
	script.Parent.StoryImage.Image = SlideImages[CurrentSlide]
	text = SlideTexts[CurrentSlide]
	Text()
end)
1 Like

It almost works, though it’s sort of fast, and the last letter is cut off which is weird.

I fixed it by adding one to NewSub’s Value in the tween and increasing the 0.04 to 0.05.

local Tween = TweenService:Create(NewSub, TweenInfo.new(0.05 * (string.len(text) + 1)), {["Value"] = string.len(text) + 1})

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.