Ai not spawning on event from another script (help needed)

Hi my ai script is supposed to spawn copies of a player at night but it doesnt spawn them at night and when it did it spammed them when its only supposed to be one im not really sure any ways around this i was connecting it to trigger from my day and night cycle script so when it would turn night it would spawn the characters after its fully designated night
this is the ai code

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local Lighting = game:GetService("Lighting")

local spawnedAIHumanoids = {}
local nightTime = false
local transitionLock = false

-- Function to create humanoid from description
local function createR6HumanoidFromDescription(humanoidDescription)
    return Players:CreateHumanoidModelFromDescription(humanoidDescription, Enum.HumanoidRigType.R6)
end

-- Function to get humanoid description from user ID
local function getHumanoidDescriptionFromUserId(userId)
    local success, description = pcall(function()
        return Players:GetHumanoidDescriptionFromUserId(userId)
    end)

    if success then
        return description
    else
        warn("Failed to get HumanoidDescription for userId:", userId)
        return nil
    end
end

-- Function to create AI humanoid
local function createAIHumanoid(player, spawnBlock)
    local userId = player.UserId
    local humanoidDescription = getHumanoidDescriptionFromUserId(userId)

    if humanoidDescription then
        local humanoidModel = createR6HumanoidFromDescription(humanoidDescription)
        if humanoidModel then
            humanoidModel.Parent = Workspace
            local spawnPosition = spawnBlock.Position + Vector3.new(0, 5, 0)
            humanoidModel:SetPrimaryPartCFrame(CFrame.new(spawnPosition))
            humanoidModel.Name = "AIHumanoid_" .. player.Name
            print("AI humanoid spawned at:", spawnPosition)

            -- Track the spawned AI humanoid
            spawnedAIHumanoids[player.UserId] = humanoidModel

            -- Setup death handling
            local humanoid = humanoidModel:FindFirstChildOfClass("Humanoid")
            if humanoid then
                humanoid.Died:Connect(function()
                    print("AI humanoid for player " .. player.Name .. " has died.")
                    spawnedAIHumanoids[player.UserId] = nil
                end)
            end
        else
            warn("Failed to create humanoid model for userId:", userId)
        end
    end
end

-- Function to generate AI humanoids
local function generateAIHumanoids()
    local players = Players:GetPlayers()
    local spawnBlocksFolder = Workspace:WaitForChild("AiSpawnBlocks")
    local spawnBlocks = spawnBlocksFolder:GetChildren()

    if #spawnBlocks == 0 then
        warn("No AiSpawnBlocks found")
        return
    end

    for _, player in ipairs(players) do
        if not spawnedAIHumanoids[player.UserId] then
            local randomSpawnBlock = spawnBlocks[math.random(1, #spawnBlocks)]
            createAIHumanoid(player, randomSpawnBlock)
        end
    end
end

-- Function to despawn AI humanoids
local function despawnAIHumanoids()
    for userId, humanoidModel in pairs(spawnedAIHumanoids) do
        if humanoidModel then
            humanoidModel:Destroy()
            spawnedAIHumanoids[userId] = nil
        end
    end
end

-- Handle player addition
Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function()
        wait(2)
        if nightTime and not spawnedAIHumanoids[player.UserId] then
            local spawnBlocksFolder = Workspace:WaitForChild("AiSpawnBlocks")
            local spawnBlocks = spawnBlocksFolder:GetChildren()
            local randomSpawnBlock = spawnBlocks[math.random(1, #spawnBlocks)]
            createAIHumanoid(player, randomSpawnBlock)
        end
    end)
end)

-- Handle player removal
Players.PlayerRemoving:Connect(function(player)
    if spawnedAIHumanoids[player.UserId] then
        spawnedAIHumanoids[player.UserId]:Destroy()
        spawnedAIHumanoids[player.UserId] = nil
    end
end)

-- Function to handle night event
local function onNightEvent()
    print("It's night now. Spawning AI...")
    nightTime = true
    generateAIHumanoids()
end

-- Function to handle day event
local function onDayEvent()
    print("It's day now. Despawning AI...")
    nightTime = false
    despawnAIHumanoids()
end

-- Detect day and night transitions
local previousTime = Lighting.ClockTime
local function detectDayNightTransition()
    local currentTime = Lighting.ClockTime
    if transitionLock then
        return
    end

    if previousTime < 18 and currentTime >= 18 then
        print("Transition to night detected.")
        transitionLock = true
        onNightEvent()
        wait(1) -- Add a slight delay to prevent multiple triggers
        transitionLock = false
    elseif previousTime < 6 and currentTime >= 6 then
        print("Transition to night detected (after midnight).")
        transitionLock = true
        onNightEvent()
        wait(1) -- Add a slight delay to prevent multiple triggers
        transitionLock = false
    elseif previousTime >= 18 and currentTime < 18 then
        print("Transition to day detected.")
        transitionLock = true
        onDayEvent()
        wait(1) -- Add a slight delay to prevent multiple triggers
        transitionLock = false
    elseif previousTime >= 6 and currentTime < 6 then
        print("Transition to day detected (after midnight).")
        transitionLock = true
        onDayEvent()
        wait(1) -- Add a slight delay to prevent multiple triggers
        transitionLock = false
    end
    previousTime = currentTime
end

Lighting:GetPropertyChangedSignal("ClockTime"):Connect(detectDayNightTransition)

-- Initial generation of AI humanoids if the server starts during the night
if Lighting.ClockTime >= 18 or Lighting.ClockTime < 6 then
    onNightEvent()
else
    onDayEvent()
end

-- Handle player death and respawn
for _, player in pairs(Players:GetPlayers()) do
    player.CharacterAdded:Connect(function(character)
        character:WaitForChild("Humanoid").Died:Connect(function()
            wait(1)
            if spawnedAIHumanoids[player.UserId] then
                spawnedAIHumanoids[player.UserId]:Destroy()
                spawnedAIHumanoids[player.UserId] = nil
            end
        end)
    end)
end
1 Like

Id appreciate some help from those who can because i actually cant think of a workaround please im really hoping to get some suggestion or push in the right direction atleast

1 Like

i forgot to add my day and night cycle script to it because i am trying to tie the functions together through seperate scripts so yeah

local Lighting = game:GetService("Lighting")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Create RemoteEvent
local nightEvent = ReplicatedStorage:FindFirstChild("NightEvent") or Instance.new("RemoteEvent", ReplicatedStorage)
nightEvent.Name = "NightEvent"

local rainEvent = ReplicatedStorage:FindFirstChild("RainEvent") or Instance.new("RemoteEvent", ReplicatedStorage)
rainEvent.Name = "RainEvent"

local stormEvent = ReplicatedStorage:FindFirstChild("StormEvent") or Instance.new("RemoteEvent", ReplicatedStorage)
stormEvent.Name = "StormEvent"

local dayDuration = 180 -- 3 minutes
local nightDuration = 900 -- 15 minutes
local fadeDuration = 10 -- Duration for smooth transition

local playerID = 321994668

-- Add or find existing day and night sounds
local daySound = Lighting:FindFirstChild("DayAmbience") or Instance.new("Sound", Lighting)
daySound.SoundId = "rbxassetid://138089070"
daySound.Looped = true
daySound.Volume = 0
daySound.Name = "DayAmbience"
daySound:Play()

local nightSound = Lighting:FindFirstChild("NightAmbience") or Instance.new("Sound", Lighting)
nightSound.SoundId = "rbxassetid://390457804"
nightSound.Looped = true
nightSound.Volume = 0
nightSound.Name = "NightAmbience"
nightSound:Play()

local intoNightSound = Lighting:FindFirstChild("IntoNight") or Instance.new("Sound", Lighting)
intoNightSound.SoundId = "rbxassetid://13061809"
intoNightSound.Looped = false
intoNightSound.Volume = 1
intoNightSound.PlaybackSpeed = 0.2
intoNightSound.Name = "IntoNight"

local itsNightSound = Lighting:FindFirstChild("ItsNight") or Instance.new("Sound", Lighting)
itsNightSound.SoundId = "rbxassetid://9043340747"
itsNightSound.Looped = false
itsNightSound.Volume = 1
itsNightSound.Name = "ItsNight"

-- Add new sounds for daytime transition
local intoDaySound1 = Lighting:FindFirstChild("IntoDay1") or Instance.new("Sound", Lighting)
intoDaySound1.SoundId = "rbxassetid://266271872"
intoDaySound1.Looped = false
intoDaySound1.Volume = 1
intoDaySound1.PlaybackSpeed = 0.9
intoDaySound1.Name = "IntoDay1"

local intoDaySound2 = Lighting:FindFirstChild("IntoDay2") or Instance.new("Sound", Lighting)
intoDaySound2.SoundId = "rbxassetid://266271872"
intoDaySound2.Looped = false
intoDaySound2.Volume = 1
intoDaySound2.PlaybackSpeed = 0.8
intoDaySound2.Name = "IntoDay2"

-- Add storm sound
local stormSound = Lighting:FindFirstChild("StormSound") or Instance.new("Sound", Lighting)
stormSound.SoundId = "rbxassetid://9120020706"
stormSound.Looped = false  -- Ensure the sound doesn't loop
stormSound.Volume = 0
stormSound.Name = "StormSound"

print("Day sound, night sound, into night sound, its night sound, and storm sound initialized and started.")
print("IntoDay sounds initialized.")

local firstDaytime = true
local isNightTransitioning = false
local isRaining = false
local isStorming = false

-- Function to show the "SURVIVE" text
local function showSurviveText()
	nightEvent:FireAllClients()
end

-- Function to smoothly change the lighting and audio
local function smoothTransition(targetBrightness, targetAmbient, targetOutdoorAmbient, targetClockTime, targetDayVolume, targetNightVolume, playIntoNight, playIntoDay, duration)
	local initialBrightness = Lighting.Brightness
	local initialAmbient = Lighting.Ambient
	local initialOutdoorAmbient = Lighting.OutdoorAmbient
	local initialClockTime = Lighting.ClockTime
	local initialDayVolume = daySound.Volume
	local initialNightVolume = nightSound.Volume
	local startTime = tick()

	-- Restart and delay playing into night sound by 0.5 seconds
	if playIntoNight then
		intoNightSound:Stop()
		intoNightSound.TimePosition = 0
		intoNightSound.Volume = 1
		intoNightSound.PlaybackSpeed = 0.2
		spawn(function()
			wait(0.5)
			print("Playing into night sound.")
			intoNightSound:Play()
		end)
	end

	-- Restart and delay playing into day sounds
	if playIntoDay and not firstDaytime then
		intoDaySound1:Stop()
		intoDaySound1.TimePosition = 0
		intoDaySound1.Volume = 1
		intoDaySound1.PlaybackSpeed = 0.9

		intoDaySound2:Stop()
		intoDaySound2.TimePosition = 0
		intoDaySound2.Volume = 1
		intoDaySound2.PlaybackSpeed = 0.8

		spawn(function()
			wait(0.5)
			print("Playing into day sounds.")
			intoDaySound1:Play()
			intoDaySound2:Play()
		end)
	end

	while tick() - startTime < duration do
		local elapsed = tick() - startTime
		local progress = elapsed / duration

		-- Update lighting properties
		Lighting.Brightness = initialBrightness + (targetBrightness - initialBrightness) * progress
		Lighting.Ambient = initialAmbient:lerp(targetAmbient, progress)
		Lighting.OutdoorAmbient = initialOutdoorAmbient:lerp(targetOutdoorAmbient, progress)
		Lighting.ClockTime = initialClockTime + (targetClockTime - initialClockTime) * progress

		-- Update audio volumes
		daySound.Volume = initialDayVolume + (targetDayVolume - initialDayVolume) * progress
		nightSound.Volume = initialNightVolume + (targetNightVolume - initialNightVolume) * progress

		-- Fade out into night sound near the end
		if playIntoNight and intoNightSound.IsPlaying and elapsed > duration - 1 then
			intoNightSound.Volume = (duration - elapsed) / 1
		end

		-- Wait a short time before the next update
		wait(0.03) -- Update more frequently for smoother transition
	end

	-- Ensure final values are set
	Lighting.Brightness = targetBrightness
	Lighting.Ambient = targetAmbient
	Lighting.OutdoorAmbient = targetOutdoorAmbient
	Lighting.ClockTime = targetClockTime
	daySound.Volume = targetDayVolume
	nightSound.Volume = targetNightVolume
	if playIntoNight then
		intoNightSound.Volume = 0
		print("Transition completed: ClockTime =", targetClockTime, "Day Volume =", targetDayVolume, "Night Volume =", targetNightVolume)
		print("It's night now.")
		wait(1)
		itsNightSound:Play()
		nightEvent:FireAllClients()  -- Fire the event to all clients
		showSurviveText()  -- Show the "SURVIVE" text when night starts
	end
end

-- Function to start the day-night cycle
local function startDayNightCycle()
	while true do
		-- Daytime (6 AM to 6 PM)
		print("Starting daytime transition.")
		if firstDaytime then
			smoothTransition(2, Color3.fromRGB(255, 255, 255), Color3.fromRGB(128, 128, 128), 14, 0.207, 0, false, false, fadeDuration)
			firstDaytime = false
		else
			smoothTransition(2, Color3.fromRGB(255, 255, 255), Color3.fromRGB(128, 128, 128), 14, 0.207, 0, false, true, fadeDuration)
		end
		wait(dayDuration)

		-- Transition to night (6 PM to 6 AM)
		print("Starting night transition.")
		isNightTransitioning = true
		smoothTransition(0, Color3.fromRGB(0, 0, 0), Color3.fromRGB(0, 0, 0), 0, 0, 0.207, true, false, fadeDuration)
		wait(nightDuration)
		isNightTransitioning = false
	end
end

-- Function to smoothly transition storm effects
local function smoothStormTransition(action, duration)
	local initialOutdoorAmbient = Lighting.OutdoorAmbient
	local targetOutdoorAmbient = action == "start" and Color3.fromRGB(0, 0, 0) or Lighting:GetAttribute("OriginalOutdoorAmbient") or Color3.fromRGB(128, 128, 128)
	local initialBrightness = Lighting.Brightness
	local targetBrightness = action == "start" and 0 or 2
	local startTime = tick()

	if action == "start" then
		stormSound:Stop()
		stormSound.TimePosition = 0
		stormSound.Volume = 3
		stormSound.Looped = false
		stormSound:Play()
	end

	while tick() - startTime < duration do
		local elapsed = tick() - startTime
		local progress = elapsed / duration

		Lighting.OutdoorAmbient = initialOutdoorAmbient:lerp(targetOutdoorAmbient, progress)
		Lighting.Brightness = initialBrightness + (targetBrightness - initialBrightness) * progress
		stormSound.Volume = action == "start" and (3 * progress) or (3 * (1 - progress)) -- Fade in/out the storm sound

		wait(0.03)
	end

	Lighting.OutdoorAmbient = targetOutdoorAmbient
	Lighting.Brightness = targetBrightness
	if action == "stop" then
		stormSound:Stop()
	end
end

-- Function to trigger rain
local function triggerRain(action)
	local initialClockTime = Lighting.ClockTime
	for _, player in ipairs(Players:GetPlayers()) do
		if action == "start" then
			rainEvent:FireClient(player, "EnableRain")
			isRaining = true

			-- 1/100 chance to start a storm when rain starts
			if math.random(1, 100) == 1 then
				triggerStorm("start")
			end

			if not isNightTransitioning and Lighting.ClockTime >= 6 and Lighting.ClockTime < 18 then
				-- Smoothly change the sky color and ClockTime during the day
				if not Lighting:GetAttribute("OriginalOutdoorAmbient") then
					Lighting:SetAttribute("OriginalOutdoorAmbient", Lighting.OutdoorAmbient)
				end
				local initialColor = Lighting.OutdoorAmbient
				local targetColor = Color3.fromRGB(58, 58, 59)
				local fadeTime = 5 -- 5 seconds fade time
				local initialBrightness = Lighting.Brightness
				local targetBrightness = initialBrightness * 0.8 -- Slightly lower brightness during rain

				spawn(function()
					local startTime = tick()
					while tick() - startTime < fadeTime do
						local elapsed = tick() - startTime
						local progress = elapsed / fadeTime
						Lighting.OutdoorAmbient = initialColor:lerp(targetColor, progress)
						Lighting.Brightness = initialBrightness + (targetBrightness - initialBrightness) * progress
						Lighting.ClockTime = initialClockTime + (6.254 - initialClockTime) * progress -- Smoothly change the ClockTime to 6.254 during rain
						wait(0.03)
					end
					Lighting.OutdoorAmbient = targetColor
					Lighting.Brightness = targetBrightness
					Lighting.ClockTime = 6.254
				end)
			else
				-- Set the sky color instantly if it's not day
				Lighting.OutdoorAmbient = Color3.fromRGB(58, 58, 59)
				Lighting.ClockTime = 23.0443 -- Set the ClockTime to 23.0443 during rain at night
			end
		elseif action == "stop" then
			rainEvent:FireClient(player, "DisableRain")
			isRaining = false

			if not isNightTransitioning and Lighting.ClockTime >= 6 and Lighting.ClockTime < 18 then
				-- Smoothly change the sky color and ClockTime back to original during the day
				local initialColor = Lighting.OutdoorAmbient
				local targetColor = Lighting:GetAttribute("OriginalOutdoorAmbient") or Color3.fromRGB(128, 128, 128)
				local fadeTime = 7 -- 7 seconds fade time
				local initialDayVolume = daySound.Volume
				local targetDayVolume = 0.207 -- Reset to original day volume

				spawn(function()
					local startTime = tick()
					while tick() - startTime < fadeTime do
						local elapsed = tick() - startTime
						local progress = elapsed / fadeTime
						Lighting.OutdoorAmbient = initialColor:lerp(targetColor, progress)
						daySound.Volume = initialDayVolume + (targetDayVolume - initialDayVolume) * progress
						Lighting.ClockTime = initialClockTime + (13.089 - initialClockTime) * progress -- Smoothly change the ClockTime back to 13.089 after rain stops
						wait(0.03)
					end
					Lighting.OutdoorAmbient = targetColor
					daySound.Volume = targetDayVolume
					Lighting.ClockTime = 13.089
				end)
			else
				-- Change the sky color back to original instantly if it's not day
				Lighting.OutdoorAmbient = Lighting:GetAttribute("OriginalOutdoorAmbient") or Color3.fromRGB(128, 128, 128)
				Lighting.ClockTime = 23.0443 -- Keep the ClockTime at 23.0443 if rain stops at night

				-- Reset nighttime settings when rain stops at night
				Lighting.Brightness = 0
				Lighting.Ambient = Color3.fromRGB(0, 0, 0)
				Lighting.OutdoorAmbient = Color3.fromRGB(26, 26, 26)
				Lighting.ColorShift_Bottom = Color3.fromRGB(0, 0, 0)
				Lighting.ColorShift_Top = Color3.fromRGB(0, 0, 0)
				nightSound.Volume = 0.207 -- Ensure night volume is set correctly
			end
		end
	end
end

-- Function to trigger storm
local function triggerStorm(action)
	for _, player in ipairs(Players:GetPlayers()) do
		if action == "start" then
			stormEvent:FireClient(player, "EnableStorm")
			isStorming = true
			smoothStormTransition("start", 10)  -- Smooth transition for storm
			-- Additional storm-specific logic can be added here (e.g., changing skybox, more intense effects)
		elseif action == "stop" then
			stormEvent:FireClient(player, "DisableStorm")
			isStorming = false
			smoothStormTransition("stop", 10)  -- Smooth transition to stop storm
			-- Additional storm-specific reset logic can be added here
		end
	end
end

-- Function to handle manual triggering of day and night
local function onChatMessage(player, message)
	if player.UserId == playerID then
		if message == ";trigger day" then
			print("Manual trigger: day")
			smoothTransition(2, Color3.fromRGB(255, 255, 255), Color3.fromRGB(128, 128, 128), 14, 0.207, 0, false, true, fadeDuration)
		elseif message == ";trigger night" then
			print("Manual trigger: night")
			smoothTransition(0, Color3.fromRGB(0, 0, 0), Color3.fromRGB(0, 0, 0), 0, 0, 0.207, true, false, fadeDuration)
			showSurviveText() -- Show the "SURVIVE" text when manually triggering night
		elseif message == ";trigger rain" then
			print("Manual trigger: rain")
			triggerRain("start")
		elseif message == ";trigger rainstop" then
			print("Manual trigger: rainstop")
			triggerRain("stop")
		elseif message == ";trigger storm" and isRaining then
			print("Manual trigger: storm")
			triggerStorm("start")
		elseif message == ";trigger stormstop" and isStorming then
			print("Manual trigger: stormstop")
			triggerStorm("stop")
		end
	end
end

-- Connect the chat event
Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(message)
		onChatMessage(player, message)
	end)
	-- Handle ongoing rain or storm for new players
	if isRaining then
		rainEvent:FireClient(player, "EnableRain")
	end
	if isStorming then
		stormEvent:FireClient(player, "EnableStorm")
	end
end)

-- Start the day-night cycle
coroutine.wrap(startDayNightCycle)()

i dont believe i need to modify the day night cycle script any further.

I got a little further it spawns a single ai right away when it’s turning “night” in game but not when i try and make it spawn on the event dedicating night which is what i want this is the code so far and am i shadow banned or something no one seems to reply to my posts for help :confused:

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local Lighting = game:GetService("Lighting")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local spawnedAIHumanoids = {}
local nightTime = false

-- Function to create humanoid from description
local function createR6HumanoidFromDescription(humanoidDescription)
    return Players:CreateHumanoidModelFromDescription(humanoidDescription, Enum.HumanoidRigType.R6)
end

-- Function to get humanoid description from user ID
local function getHumanoidDescriptionFromUserId(userId)
    local success, description = pcall(function()
        return Players:GetHumanoidDescriptionFromUserId(userId)
    end)

    if success then
        return description
    else
        warn("Failed to get HumanoidDescription for userId:", userId)
        return nil
    end
end

-- Function to create AI humanoid
local function createAIHumanoid(player, spawnBlock)
    local userId = player.UserId
    local humanoidDescription = getHumanoidDescriptionFromUserId(userId)

    if humanoidDescription then
        local humanoidModel = createR6HumanoidFromDescription(humanoidDescription)
        if humanoidModel then
            humanoidModel.Parent = Workspace
            local spawnPosition = spawnBlock.Position + Vector3.new(0, 5, 0)
            humanoidModel:SetPrimaryPartCFrame(CFrame.new(spawnPosition))
            humanoidModel.Name = "AIHumanoid_" .. player.Name
            print("AI humanoid spawned at:", spawnPosition)

            -- Track the spawned AI humanoid
            spawnedAIHumanoids[player.UserId] = humanoidModel

            -- Setup death handling
            local humanoid = humanoidModel:FindFirstChildOfClass("Humanoid")
            if humanoid then
                humanoid.Died:Connect(function()
                    print("AI humanoid for player " .. player.Name .. " has died.")
                    spawnedAIHumanoids[player.UserId] = nil
                end)
            end
        else
            warn("Failed to create humanoid model for userId:", userId)
        end
    end
end

-- Function to generate AI humanoids
local function generateAIHumanoids()
    local players = Players:GetPlayers()
    local spawnBlocksFolder = Workspace:FindFirstChild("AiSpawnBlocks")

    if not spawnBlocksFolder then
        warn("No AiSpawnBlocks folder found")
        return
    end

    local spawnBlocks = spawnBlocksFolder:GetChildren()
    if #spawnBlocks == 0 then
        warn("No AiSpawnBlocks found")
        return
    end

    for _, player in ipairs(players) do
        if not spawnedAIHumanoids[player.UserId] then
            local randomSpawnBlock = spawnBlocks[math.random(1, #spawnBlocks)]
            createAIHumanoid(player, randomSpawnBlock)
        end
    end
end

-- Function to despawn AI humanoids
local function despawnAIHumanoids()
    for userId, humanoidModel in pairs(spawnedAIHumanoids) do
        if humanoidModel then
            humanoidModel:Destroy()
            spawnedAIHumanoids[userId] = nil
        end
    end
end

-- Handle player addition
Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function()
        wait(2)
        if nightTime and not spawnedAIHumanoids[player.UserId] then
            local spawnBlocksFolder = Workspace:FindFirstChild("AiSpawnBlocks")
            local spawnBlocks = spawnBlocksFolder:GetChildren()
            local randomSpawnBlock = spawnBlocks[math.random(1, #spawnBlocks)]
            createAIHumanoid(player, randomSpawnBlock)
        end
    end)
end)

-- Handle player removal
Players.PlayerRemoving:Connect(function(player)
    if spawnedAIHumanoids[player.UserId] then
        spawnedAIHumanoids[player.UserId]:Destroy()
        spawnedAIHumanoids[player.UserId] = nil
    end
end)

-- Function to handle night event
local function onNightEvent()
    print("It's night now. Spawning AI...")
    nightTime = true
    generateAIHumanoids()
end

-- Function to handle day event
local function onDayEvent()
    print("It's day now. Despawning AI...")
    nightTime = false
    despawnAIHumanoids()
end

-- Detect day and night transitions
local function detectDayNightTransition()
    local currentTime = Lighting.ClockTime
    if currentTime >= 18 or currentTime < 6 then
        if not nightTime then
            onNightEvent()
        end
    else
        if nightTime then
            onDayEvent()
        end
    end
end

Lighting:GetPropertyChangedSignal("ClockTime"):Connect(detectDayNightTransition)

-- Initial generation of AI humanoids if the server starts during the night
if Lighting.ClockTime >= 18 or Lighting.ClockTime < 6 then
    onNightEvent()
else
    onDayEvent()
end

-- Handle player death and respawn
for _, player in pairs(Players:GetPlayers()) do
    player.CharacterAdded:Connect(function(character)
        character:WaitForChild("Humanoid").Died:Connect(function()
            wait(1)
            if spawnedAIHumanoids[player.UserId] then
                spawnedAIHumanoids[player.UserId]:Destroy()
                spawnedAIHumanoids[player.UserId] = nil
            end
        end)
    end)
end

I have not found any solutions yet, but as I can clearly see I am drowning in help.