DontDestroy
Coding Style wiki
DontDestroy 為跨場景常駐物件標記組件,於 Awake 時將物件依 Inspector 配置的 Runtime Name 重新命名,並執行 DontDestroyOnLoad 使其切換場景時不被銷毀。
| 命名空間 | OxGKit.Utilities.DontDestroy |
| 類型 | public class DontDestroy : MonoBehaviour |
| 原始碼 | DontDestroy.cs |
using OxGKit.Utilities.DontDestroy;
注意 DontDestroyOnLoad 僅對根物件 (Root GameObject) 生效,請將本組件掛載於場景根層級的物件上 (同物件僅允許一個, DisallowMultipleComponent)。
快速上手
- 透過 AddComponentMenu: OxGKit/Utilities/DontDestroy/DontDestroy 將組件掛載於根物件。
- 於 Inspector 配置 Runtime Name (預設
DontDestroy),Awake時物件會自動改名並標記為常駐。
using OxGKit.Utilities.DontDestroy;
using UnityEngine;
public class DontDestroyDemo : MonoBehaviour
{
private void Start()
{
var dontDestroy = this.GetComponent<DontDestroy>();
// 執行時重新命名物件
dontDestroy.SetRuntimeName("GameManager");
}
}
方法
SetRuntimeName
public void SetRuntimeName(string runtimeName)
以指定名稱重新命名物件 (同步更新 GameObject 名稱與內部記錄的 Runtime Name)。