跳到主要内容

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)。

快速上手

  1. 通过 AddComponentMenu: OxGKit/Utilities/DontDestroy/DontDestroy 将组件挂载于根对象
  2. 于 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)。