Home > Net >  Any ideas on how to make this code efficient?
Any ideas on how to make this code efficient?

Time:03-29

The code:


local RunService = game:GetService("RunService")
local Player = game.Players:GetPlayerFromCharacter(script.Parent)
local Character = Player.Character or Player.CharacterAdded:Wait()
local PartDimensions = Vector3.new(2048,512,2048)
local WaterPart = Instance.new("Part")
WaterPart.Size = PartDimensions
WaterPart.CFrame = CFrame.new(Character.HumanoidRootPart.Position.X,-2048,Character.HumanoidRootPart.Position.Z)
WaterPart.Material = Enum.Material.Foil
WaterPart.CanCollide = false
WaterPart.Parent = game.Workspace
WaterPart.Anchored = true
WaterPart.Transparency = 1
Character.Humanoid.Died:Connect(function()
    WaterPart:Destroy()
end)
RunService.Stepped:Connect(function(step)
    WaterPart.CFrame = CFrame.new(Character.HumanoidRootPart.Position.X,0,Character.HumanoidRootPart.Position.Z)
    workspace.Terrain:FillBlock(WaterPart.CFrame, WaterPart.Size, Enum.Material.Water)

I made an code to generate water I expected it to work good enough The code almost crashes the server

CodePudding user response:

It's unclear why you are filling up the world with water where the player walks, but way below where they normally spawn, and with an absolutely massive brush. But there are likely a few things slowing down this script.

1. Do the work ahead of time

Filling terrain is generally a slow operation. When the engine creates terrain like this, it has to do a ton of voxel calculations to create a mesh for the new terrain. One way you can offset this is to "pre-fill" the spawning area. If you know players are going to spawn at (0, 0, 0), then manually fill in the (2048, 512, 2048) region at (0, -2048, 0) at the start of the game, or bake it into the level.

2. Reduce the size of your paint brush

Consider reducing the dimensions of the WaterPart. Even if the terrain is already water, the engine still has to inspect every voxel in the specified region to see what kind of terrain it is, and the current dimensions of the WaterPart are massive! So if you reduce the size of the region, the engine will likely have more luck keeping up as it will have less work to do every step of the engine.

local PartDimensions = Vector3.new(20, 5, 20)

3. Only update the terrain when you need to

You can limit the impact of terrain generation by only adding terrain when you need to. Consider saving the dimensions of the terrain you've already added, and only add more terrain as players approach the edges.

  • Related