Need help with creating a random event system

I’m trying to create a system that spawns random events every few seconds, and when a new event starts the one before him ends, for example: a meteor shower event ends right when a zombie apocalypse event starts.

The code:

local eventTime = 15
local timer = 0

local events = {
	{
		name = "Meteor Shower",
		f = function()
			local spawns = game.Workspace.SkyEventSpawns:GetChildren()
			
			repeat
			while wait(0.5) do
				local randomPos = spawns[math.random(1, #spawns)]
				local meteorClone = game.ReplicatedStorage.Meteor:Clone()
				meteorClone.Parent = workspace
				meteorClone.PrimaryPart.Position = randomPos.Position
				end
			until wait(eventTime)
		end
	},
	{
		name = "Zombie Apocalypse",
		f = function()
			local spawns = game.Workspace.Targets:GetChildren()

			for _, spawnPoint in pairs(spawns) do
				local spawnPos = spawnPoint.Position
				local zombie = game.ReplicatedStorage.Zombie:Clone()
				zombie.Parent = workspace
				zombie:WaitForChild("Charcter"):FindFirstChild("HumanoidRootPart").CFrame.Position = spawnPos
			end
		end
	}
}

local runEvent = runService.Heartbeat:Connect(function(dt)
	if isInRound.Value == true then
		timer += dt

		if timer > eventTime then
			timer = timer % eventTime

			local event_index = math.random(#events)

			local event = events[event_index]
			local event_name = event.name
			local event_f = event.f

			print("There is a " .. event_name)
			event_f()
		end
	end
end)

The issues I have are that the events don’t stop when another one starts, and the zombie apocalypse event only spawns one zombie instead of a zombie for each spawn point.

I would create a wait or a value.
For example, I would have a value that is a Boolean, that is called “EventHappening”, make it true when a event starts, and false when an event ends, and it can only starts an event with
EventHappening.Changed:Connect(function()
end)

Why not just do this?

local events = {}

events[1] = {name = "zombie apocalypse"; f = function()
	local debounce = true
	task.spawn(function()
		task.wait(2)
		debounce = false
	end)
	while debounce do
		print(events[1].name)
		task.wait()
	end
end,}

events[2] = {name = "meteor shower"; f = function()
	local debounce = true
	task.spawn(function()
		task.wait(2)
		debounce = false
	end)
	while debounce do
		print(events[2].name)
		task.wait()
	end
end,}

while true do
	task.spawn(function()
		events[math.random(1,#events)]:f()
	end)
	task.wait(2)
end
2 Likes

And where to put the actual function of the event?

I put the code inside the while debounce do loop, and it still doesn’t work.

I tested it and it worked.

You make a function in the table.

For some reason it doesn’t work for me, and there are no errors in the console.

I managed to find fix it, thanks

1 Like