Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

屬性目標中的效能提示

前言

As explained in the 除錯工具 documentation, Godot features a Debugger > Monitors bottom panel that allows tracking various values with graphs showing their evolution over time. The data for those graphs is sourced from the engine's Performance singleton.

Since Godot 4.0, you can declare custom values to be displayed in the Monitors tab. Example use cases for custom performance monitors include:

  • 顯示特定於您的專案的績效指標。例如,在體素遊戲中,您可以建立一個效能監視器來追蹤每秒載入的區塊數。

  • 顯示與效能不嚴格相關的遊戲內指標,但對於出於除錯目的繪製圖表仍然有用。例如,您可以追蹤遊戲中存在的敵人數量,以確保您的生成機制能如預期運作。

建立自定節點

在此範例中,我們將建立一個自訂效能監視器來追蹤目前正在運作的專案中存在多少敵人。

主場景有一個 class_Timer 節點,並附有以下腳本:

extends Timer


func _ready():
    # The slash delimiter is used to determine the category of the monitor.
    # If there is no slash in the monitor name, a generic "Custom" category
    # will be used instead.
    Performance.add_custom_monitor("game/enemies", get_enemy_count)
    timeout.connect(_on_timeout)
    # Spawn 20 enemies per second.
    wait_time = 0.05
    start()


func _on_timeout():
    var enemy = preload("res://enemy.tscn").instantiate()
    get_parent().add_child(enemy)


# This function is called every time the performance monitor is queried
# (this occurs once per second in the editor, more if called manually).
# The function must return a number greater than or equal to 0 (int or float).
func get_enemy_count():
    return get_tree().get_nodes_in_group("enemies").size()

The second parameter of Performance.add_custom_monitor is a Callable.

enemy.tscn 是一個具有 Node2D 根節點和 Timer 子節點的場景。 Node2D 附加了以下腳本:

extends Node2D


func _ready():
    add_to_group("enemies")
    $Timer.timeout.connect(_on_timer_timeout)
    # Despawn enemies 2.5 seconds after they spawn.
    $Timer.wait_time = 2.5
    $Timer.start()


func _on_timer_timeout():
    queue_free()

在此範例中,由於我們每秒生成 20 個敵人,並且每個敵人在生成後 2.5 秒後消失,因此我們預計場景中存在的敵人數量將穩定為 50 個。我們可以透過查看圖表來確定這一點。

若要視覺化從此自訂效能監視器建立的圖形,請執行專案,在專案執行時切換到編輯器,然後開啟編輯器視窗底部的 偵錯器 > 監視器。向下捲動到新推出的**遊戲**部分並選中**敵人**。您應該會看到如下所示的圖表:

Example editor graph from a custom performance monitor

Example editor graph from a custom performance monitor

備註

效能監視器處理程式碼不必與節點本身位於同一腳本中。您可以選擇將效能監視器註冊和 getter 函式移至 autoload <doc_singletons_autoload>`。

效能偵測工具。

如果您希望在正在執行的專案的視窗(而不是編輯器)中顯示效能監視器的值,請使用 Performance.get_custom_monitor("category/name")`` 來取得自訂監視器的值。您可以使用 class_Label、class_RichTextLabel、doc_custom_drawing_in_2d、doc_3 d_text 等顯示值。

此方法也可用於匯出的專案(偵錯和發布模式),它允許您在編輯器外部建立視覺化效果。