Is there any easier way to execute this?

I have a script for an AI, and whenever it’s jumpscaring I instantly stop it from patroling, break the task.wait() loop and spawn in a new AI script. Is there an easier way of doing this, preferably without making a new script?

Main ServerScript in AI model

while task.wait() do
	if AI.Jumpscaring.Value == false then
		patrol()
	else
		warn("Jumpscaring")
		break
	end
end

Kill ServerScript in AI model

AI.Main:Destroy()

local ClonedAI = script.Main:Clone()
ClonedAI.Parent = AI
ClonedAI.Enabled = true

You can use coroutines to stop and start infinite loops all in one script

1 Like

Ah gotcha, would it be possible for some sample code? Or are there any good sources for coroutines as I never really worked with them before. But regardless, thank you for the idea!

https://www.lua.org/pil/9.1.html

1 Like

Thanks a lot! Will definitely try it out.

You can use coroutines for this but task.spawn is better for this since you don’t need the overhead of coroutines.

Code:

task.spawn(function()
	while task.wait() do
		if AI.Jumpscaring.Value == false then
			patrol()
		else
			warn("Jumpscaring")
			break
		end
	end
end)

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