how to use dont destroy on load only on objects only on certian scenes

my player character as well as my music component in game has this simple don’t destroy on load script attached, but for some scenes I want the character to destroy on load. for example, when I go back to the menu scene, I don’t want my character appearing there. is there some way to specify which scenes to not destroy on load, or maybe add a script specific to each scene instead of each gameobject?

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

public class dontdestroyonload : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        DontDestroyOnLoad(gameObject);
    }
}

Then just Destroy him when you want. There is no un-DontDestroyOnLoad().

yes but how do i write a script like that. as in if a specific scene loads dont destroy.

The SceneManager has an event for scene loading which you can register to. Register your Character to it and if it detects that the menu scene has been loaded then destroy it.

1 Like