Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

infinitely generated rooms, works in studio but not in-game. why is this?

Asked by
Foxxive 10
3 years ago
Edited 3 years ago

hi, i have a code that creates a new room as you walk along, the point of the game is just to open doors infinitely.

this is my code:

local Players = game:GetService("Players")

local visited = {}

local function OnCharacterAdded(char)
    while char.Humanoid.Health > 0 do
        wait(0.1)
        for i = -25,1 do
            local zPos = math.floor((char.HumanoidRootPart.Position.Z + i * 100) / 100 + 0.5) * 20
            if visited[zPos] == nil then
                visited[zPos] = script.Room:Clone()
                local p = visited[zPos]

                p:SetPrimaryPartCFrame(CFrame.new(Vector3.new(0,1.5,zPos)))

                p.Parent = workspace.Room
            end
        end
    end
end

local function OnPlayerAdded(plr)
    if plr.Character then
        OnCharacterAdded(plr.Character)
    end
    plr.CharacterAdded:Connect(OnCharacterAdded)
end

for _, Player in ipairs(Players:GetPlayers()) do
    OnPlayerAdded(Player)
end

Players.PlayerAdded:Connect(OnPlayerAdded)

it only works in studio for some reason, and in-game it gives me errors along the lines of "execution time exhausted" and I have no idea how to fix it.

i've made several posts on the dev forums and got no help, so I'm posting here in hopes of getting an actual answer that helps

thank you

1 answer

Log in to vote
1
Answered by 3 years ago

"Execution time exhausted" is an error that you get when you forgot to put a wait() (wait 1 frame) on a loop. Lua is a language that runs very fast, to fix it replace all your code with this or just straight up put a wait() at the end of every loop:

local Players = game:GetService("Players")

    local visited = {}

    local function OnCharacterAdded(char)
        while char.Humanoid.Health > 0 do
            wait(0.1)
            for i = -25,1 do
                local zPos = math.floor((char.HumanoidRootPart.Position.Z + i * 100) / 100 + 0.5) * 20
                if visited[zPos] == nil then
                    visited[zPos] = script.Room:Clone()
                    local p = visited[zPos]

                    p:SetPrimaryPartCFrame(CFrame.new(Vector3.new(0,1.5,zPos)))

                    p.Parent = workspace.Room
                     end
            wait()
                end
        wait()
        end
    end

    local function OnPlayerAdded(plr)
        if plr.Character then
            OnCharacterAdded(plr.Character)
        end
        plr.CharacterAdded:Connect(OnCharacterAdded)
    end

    for _, Player in ipairs(Players:GetPlayers()) do
            OnPlayerAdded(Player)
    wait()
end

    Players.PlayerAdded:Connect(OnPlayerAdded)

It's basically the same code however all the loops have a wait() inside.

Ad

Answer this question