SceneManager issue stutters on re-loading scenes

I have a few scenes that load sequentially in single mode using a SceneManager script, and after the last scene the level is reset to re-load the first scene. The issue is after the first time around when each new scene loads it stutters, and the more times you loop around the worse the stutter gets. The only component set to DontDestroyOnLoad is the SceneManager, attached to an empty game object, so all scenes should be getting destroyed when a new scene is loaded. Any clues to why this stutter is happening would be appreciated. Here is the SceneManager script:

#pragma strict
import UnityEngine.SceneManagement;
private var counter =0;
private var level:int=0;
private var created = false;
function Start () {
     if (!created) {
         DontDestroyOnLoad(this.gameObject);
         created = true;
     }
}

function Update () {
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began || Input.GetMouseButtonDown(0)) {
        counter++;
        if(counter==9){
//        Debug.Log(level);
            if(level<2) {
                level++;
                ChangeLevel(level);
            } else {
                level=0;
                ChangeLevel(level);
            }
            counter=0;
        }
    }
}

function ChangeLevel(newLevel:int) {
    var fadeTime = GetComponent(Fade).BeginFade(1);
    yield WaitForSeconds(fadeTime);
//    Debug.Log(newLevel);
    SceneManager.LoadSceneAsync(newLevel,LoadSceneMode.Single);
}

I think your ‘created’ variable doesn’t really do anything. Start is only called when the script is enabled. So it gets called once and then never again. If you create another Manager ‘created’ will be false again and you’ll end up with two Managers that aren’t destroyed on load.
I’m guessing you were trying to implement a Singleton pattern? That would be more like

static var instance = null;

private void Awake()
{
    if (instance)
       Destroy(gameObject);
    else
        instance = this;

    DontDestroyOnLoad(gameObject);
}

Not sure if this is how JavaScript works though - the static var thing might be slighly different. Also do this in Awake instead of Start, so it does this before everything else.

Anyway - this might also be the problem you’re facing. When you loop around to the first scene you have two Managers. The next cycle you’re at 3, and so on.

1 Like

Thanks Zephus, that makes sense. I’ll try it later and let you know if it solves it. Thanks!

Works perfectly, thanks! The only difference in JavaScript is to use function instead of void.