Certain line of code not working until after a certain amount of time

Hi! So I was just messing around with a project, and came across an error. When you step on a plate that activates the script, a light turns on that shines on you, and your screen goes black, and you die. Unfortunately, the screen turning black apparently happens after you die, but it is supposed to happen before you die. Here is the code:

local light = game.Workspace.Light.SurfaceLight

function spawnGui()
	local gui = Instance.new("ScreenGui")
	gui.Parent = game.StarterGui
	local newframe = Instance.new("Frame")
	newframe.Parent = gui
	newframe.BackgroundColor3 = Color3.fromRGB(0,0,0)
	newframe.Size = UDim2.new(1,0, 1,0)
	
end

script.Parent.Touched:Connect(function(hit)
	if game.Players:GetPlayerFromCharacter(hit.Parent) then
		hit.Parent.Humanoid.WalkSpeed = 0
		hit.Parent.Humanoid.JumpPower = 0
		wait(1)
		light.Enabled = true
		wait(1)
		spawnGui()
		wait(3)
		hit.Parent.Humanoid.Health = 0
	end
end)

You need to parent your ScreenGui instead to the players PlayerGui not the StarterGui because the starter gui doesn’t replicate until you’re reloaded or first join the game.

How can I do this in a script?

You can get the player by using the service Players.

local Player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)

spawnGui(Player) --// Send the player as a parameter

function spawnGui(player)
	local gui = Instance.new("ScreenGui")
	gui.Parent = player:FindFirstChild("PlayerGui")

	local newframe = Instance.new("Frame")
	newframe.Parent = gui
	newframe.BackgroundColor3 = Color3.fromRGB(0,0,0)
	newframe.Size = UDim2.new(1,0, 1,0)
end