以下の内容はhttps://bluebirdofoz.hatenablog.com/entry/2026/02/04/235303より取得しました。


UnityのDontDestroyOnLoad関数でシーンを跨いで存在できるオブジェクトを生成する

本日はUnityの小ネタ枠です。
UnityのDontDestroyOnLoad関数でシーンを跨いで存在できるオブジェクトを生成する方法です。

DontDestroyOnLoad

DontDestroyOnLoad関数はDontDestroyOnLoadの領域にゲームオブジェクトを移動します。
本関数を利用するとシーンが切り替わってもゲームオブジェクトを破棄せずに保持し続けることができます。
docs.unity3d.com

利用例

例えばSingletonパターンのコンポーネントを作成する場合、インスタンス生成時に本関数を実行します。
これにより、シーンを移動してもインスタンスが破棄されず、継続してアクセスすることが可能です。

以下のサンプルスクリプトを作成しました。
・TestSingleton.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestSingleton : MonoBehaviour
{
    // 本クラスはシーンを跨いでオブジェクトを保持するテスト用のシングルトンです。
    private static TestSingleton instance;
    public static TestSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                GameObject singletonObject = new GameObject("TestSingleton");
                instance = singletonObject.AddComponent<TestSingleton>();
                DontDestroyOnLoad(singletonObject);
            }
            return instance;
        }
    }

    private void Awake()
    {
        // シングルトンのインスタンスが既に存在する場合、重複を防ぐために新しいインスタンスを破棄します。
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else if (instance != this)
        {
            Destroy(this.gameObject);
        }
    }

    public void TestMethod()
    {
        Debug.Log("TestSingleton method called.");
    }
}

作成したスクリプトをシーン内の任意のオブジェクトに設定します。

シーンを再生するとDontDestroyOnLoadが実行され、DontDestroyOnLoadの領域にゲームオブジェクトが移動します。
DontDestroyOnLoadの領域はシーン遷移しても引き継がれるため、ゲームオブジェクトが破棄されません。




以上の内容はhttps://bluebirdofoz.hatenablog.com/entry/2026/02/04/235303より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14