垃圾清理服務可以保證在不放棄的情況下對對象進行保證摧毀。
優點
除了創建一點混亂之外,不再需要的對象可以使用系統記憶並導致體驗隨著時間推移速度降低。因此,總是建議在不再需要對象時呼叫 Instance:Destroy() 。然而,在某些情況下,對象可能會在被摧毀之前擁有特定的使用期。
考慮將牆壁粉碎成單獨的磚塊。如果你想讓磚塊在被摧毀之前停留 3 秒,你可以使用以下代碼:
task.wait(3)brick:Destroy()
然而,等待會導致線程產生,可能不是所需的。為了避免放棄,回調功能可以在 3 秒後在新線程上運行:
task.delay(3, function()
brick:Destroy()
end)
或者在一行中:
task.delay(3, brick.Destroy, brick)
雖然這現在避免了屈服,但預定的回調將永遠不會運行,如果在回調執行前停用或毀滅腳本。
這是 Debris 有特定優勢的地方,因為它不會產生當前線程,並且在腳指令碼的上下文之外運行,因此即使腳本被禁用或毀滅,也保證最終還是會毀滅實例。以下代碼不會產生,且保證實例將被摧毀:
Debris:AddItem(brick, 3)
請注意,Debris 有一個硬編碼的最大值為 1,000 個物件,因此如果添加超過 1,000 個項目,最舊的碎片將立即被摧毀,以讓位置留出新廢棄物。
範例程式碼
Creates parts on a loop and parents them to the Workspace, then uses Debris.AddItem to clean them up.
local Debris = game:GetService("Debris")
local ball = Instance.new("Part")
ball.Anchored = false
ball.Shape = Enum.PartType.Ball
ball.TopSurface = Enum.SurfaceType.Smooth
ball.BottomSurface = Enum.SurfaceType.Smooth
ball.Size = Vector3.new(1, 1, 1)
local RNG = Random.new()
local MAX_VELOCITY = 10
while true do
local newBall = ball:Clone()
newBall.BrickColor = BrickColor.random()
newBall.CFrame = CFrame.new(0, 30, 0)
newBall.Velocity =
Vector3.new(RNG:NextNumber(-MAX_VELOCITY, MAX_VELOCITY), 0, RNG:NextNumber(-MAX_VELOCITY, MAX_VELOCITY))
newBall.Parent = game.Workspace
Debris:AddItem(newBall, 2)
task.wait(0.1)
end
概要
方法
為指定的 Instance 安排在指定的生命週期內摧毀。
屬性
方法
AddItem
為指定的 Instance 安排在指定的生命週期內摧毀。在 lifetime 參數過期之後,對象以相同的方式被摧毀,即 Instance:Destroy() 。請注意,lifetime 參數是可選的,默認值為 10 秒。
請注意,Debris 有一個硬編碼的最大值為 1,000 個物件,因此如果添加超過 1,000 個項目,最舊的碎片將立即被摧毀,以讓位置留出新廢棄物。這意味著您應該將 lifetime 參數視為 最長生命時間 ,而不是準確生命時間。
參數
返回
範例程式碼
Creates parts on a loop and parents them to the Workspace, then uses Debris.AddItem to clean them up.
local Debris = game:GetService("Debris")
local ball = Instance.new("Part")
ball.Anchored = false
ball.Shape = Enum.PartType.Ball
ball.TopSurface = Enum.SurfaceType.Smooth
ball.BottomSurface = Enum.SurfaceType.Smooth
ball.Size = Vector3.new(1, 1, 1)
local RNG = Random.new()
local MAX_VELOCITY = 10
while true do
local newBall = ball:Clone()
newBall.BrickColor = BrickColor.random()
newBall.CFrame = CFrame.new(0, 30, 0)
newBall.Velocity =
Vector3.new(RNG:NextNumber(-MAX_VELOCITY, MAX_VELOCITY), 0, RNG:NextNumber(-MAX_VELOCITY, MAX_VELOCITY))
newBall.Parent = game.Workspace
Debris:AddItem(newBall, 2)
task.wait(0.1)
end