Here's my current script on my infinite tunnel with some optimizations. When I spawn in, the tunnel spawns but faces the wrong way.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TunnelSegment = ReplicatedStorage:WaitForChild("TunnelSegment")
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local segmentLength = 100
local maxSegments = 5
local segmentsLoaded = {}
local player = Players.LocalPlayer
local character = nil
local rootPart = nil
player.CharacterAdded:Connect(function(char)
character = char
rootPart = character:WaitForChild("HumanoidRootPart")
end)
if player.Character then
character = player.Character
rootPart = character:WaitForChild("HumanoidRootPart")
end
local function spawnSegment(cframe)
local newSegment = TunnelSegment:Clone()
newSegment:SetPrimaryPartCFrame(cframe)
newSegment.Parent = Workspace
table.insert(segmentsLoaded, newSegment)
end
local function updateTunnel()
if not rootPart then return end
local lastSegment = segmentsLoaded[#segmentsLoaded]
if lastSegment then
local distance = rootPart.Position.Z - lastSegment.PrimaryPart.Position.Z
if distance > -segmentLength then
local nextCFrame = lastSegment.PrimaryPart.CFrame * CFrame.new(0, 0, segmentLength)
spawnSegment(nextCFrame)
end
else
local startCFrame = rootPart.CFrame * CFrame.new(0, 0, 20)
spawnSegment(startCFrame)
end
if #segmentsLoaded > maxSegments then
local oldSegment = table.remove(segmentsLoaded, 1)
oldSegment:Destroy()
end
end
RunService.RenderStepped:Connect(function()
updateTunnel()
end)