How to end the function DontDestroyOnLoad when changing to a scene?

void Awake()
{
DontDestroyOnLoad(gameObject);
Scene scene = SceneManager.GetActiveScene();

     if (scene.name == "Level 1")
     {
           Destroy(gameObject);
           Debug.Log("I am inside the if statement");
     }

I can Destroy the gameObject outside the if statment but not inside it. What is with that? Thanks for your help in advance!!!

AFAIK there is no undo for DontDestroyOnLoad(), you have to manually destroy the object later.

It seems what you really want to do is destroy an existing instance when a new scene is loaded, but the Awake() method is only called once when an object is created.

You should put your code in the OnSceneLoaded() method which you need to add as a listener callback (delegate) to the SceneManager.

void Awake()
{
     DontDestroyOnLoad(gameObject);
     SceneManager.sceneLoaded += OnSceneLoaded;
}

void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) {
      if (scene.name == "Level 1") {
            Destroy(gameObject);
            Debug.Log("I am inside the if statement");
      }
}

Y̶o̶u̶ ̶s̶h̶o̶u̶l̶d̶ ̶b̶e̶ ̶u̶s̶i̶n̶g̶ ̶t̶h̶i̶s̶:̶ ̶ ̶

Application.loadedLevelName

̶I̶t̶ ̶r̶e̶t̶u̶r̶n̶s̶ ̶t̶h̶e̶ ̶l̶a̶s̶t̶ ̶l̶o̶a̶d̶e̶d̶ ̶s̶c̶e̶n̶e̶.̶

EDIT:
It is old and should not be used. Make sure awake is really called once new scene is loaded and make sure everything is written in the right case letters