Is OnLevelWasLoaded supposed to be called twice when using DontDestroyOnLoad?

I notice if I use DontDestroyOnLoad then OnLevelWasLoaded is called twice. I’ve tested this using Windows 7 x64 Unity v4.1.3f3.

In gameobject’s that aren’t using DontDestroyOnLoad then OnLevelWasLoaded gets called only once.

Anyone else experiencing this?

This is an interesting output from a game object that uses DontDestroyOnLoad:

    private bool runOnce = true;
    void OnLevelWasLoaded ( int level )
    {
        print ( "here" );
        if ( runOnce )
        {
            runOnce = false;
            print ( "runOnce " + runOnce );

        }
        else
        {
            print ( "else statement" );       
            runOnce = true;
        }
    }

Output:
here
runOnce false
here
runOnce false

If I do this it only prints out once…

private bool runOnce = false;
    void OnLevelWasLoaded ( int level )
    {
        if ( runOnce )
            return;

        runOnce = true;
        StartCoroutine ( Tester ( ) );
        
    }
    
    IEnumerator Tester ( )
    {
        yield return new WaitForSeconds ( 1 );
        print ( "TESTING" );
    }

You will have 2 gameobjects cause u dont destroy the old one and a new instance of the old gameobject will be created too

Just a simple check like the line below caught the duplicate (if you’re using a singleton pattern):

if( this != instance ) return;

using UnityEngine;
using System.Collections;

            public class Foo : MonoBehaviour {
            
            	private static Foo m_Instance;
            	
            	public static Foo instance {
            		get {
            			if(m_Instance == null) {
            				m_Instance = GameObject.FindObjectOfType<Foo>();
            				DontDestroyOnLoad(m_Instance.gameObject);
            			}
            			
            			return m_Instance;
            		}
            	}
            	
            	public override void Awake() {
            		if(m_Instance == null) {
            			m_Instance = this;
            			DontDestroyOnLoad(gameObject);
            		}else {
            			Destroy(gameObject);
            		}
            	}
            
            	void OnLevelWasLoaded(int level) {
            		if(m_Instance == this) {
            			Debug.Log(" Static Instance OnLevelWasLoaded is called");
            		} 
            	}
            }

I have this script attached to a game object in my scene. When I reload the scene in code, I see that OnLevelWasLoaded is called 2 times, but the Debug.Log statement is only hit once. So from my understanding, when a scene is loaded new instance of the script is created. The OnLevelWasLoaded is called once for each of the two instances of the script.