How can I make infinite chunk generation

So I’m using this code to make Perlin noise and generate block terrain but Idk how to make it generate and ungenerate as the player traverses the terrain how can I achieve this?

this is my code

--//Locals

local X = 64 --How big the terrain can be on the X value

local Z = 64 --How big the terrain can be on the Z value

local grid = {}

--//Main

for x = 1, X do --//2D array will tell the grid how to place the blocks on the axis.
    grid[x] = {}

    for z = 1, Z do
	    grid[x][z] = math.noise(x/10, z/10) * 10 --randomness of the block placing.
    end
end

for x = 1, X do --Use the 2d array and turn them into parts and put them in the workspace.
    for z = 1, Z do
	    local yPos = grid[x][z]
	
	    local part = Instance.new("Part")
	    local spawnPart = Instance.new("SpawnLocation")
	    spawnPart.Parent = game.ReplicatedStorage
	    part.Anchored = true
	
	    if yPos < -9 then --Sets the sand texture
		    part.Material = Enum.Material.Sand
		    part.BrickColor = BrickColor.new("Cool yellow")
		    part.Name = "SandPart"
		    part.Parent = workspace.blockTerrain.Sand
	    elseif yPos < 0 then --Sets the variety dark grass texture
		    part.Material = Enum.Material.Grass
	    	    part.BrickColor = BrickColor.new("Dark green")
	    	    part.Name = "DarkGrassPart"
	    	    part.Parent = workspace.blockTerrain.Grass.DarkGrass
	    else --Sets the variety green grass texture
		    part.Material = Enum.Material.Grass
		    part.BrickColor = BrickColor.new("Camo")
		    part.Name = "GreenGrassPart"
		    part.Parent = workspace.blockTerrain.Grass.GreenGrass
	    end
	
	    part.Position = Vector3.new(x*5, yPos, z*5)
	    part.Size = Vector3.new(5, 30, 5)
	
    end
end

local water = Instance.new("Part") --Adds water to the terrain
water.Anchored = true
water.Size = Vector3.new(X*5, 30, Z*5)
water.Position = Vector3.new(((X+1)*5)/2, -11,  ((Z+1)*5)/2)
water.CanCollide = false
water.Transparency = .5
water.TopSurface = Enum.SurfaceType.SmoothNoOutlines
water.LeftSurface = Enum.SurfaceType.SmoothNoOutlines
water.RightSurface = Enum.SurfaceType.SmoothNoOutlines
water.BackSurface = Enum.SurfaceType.SmoothNoOutlines
water.FrontSurface = Enum.SurfaceType.SmoothNoOutlines
water.BottomSurface = Enum.SurfaceType.SmoothNoOutlines
water.BrickColor = BrickColor.new("Pastel Blue")
water.Parent = workspace.blockTerrain.Water
water.Name = "WaterPart"
1 Like