Fading between scenes

I’m stuck on fading between scenes. Basically I’ve got some explosion stuff in my game scene that happens when the game ends, but I want this to happen as the scene is fading to the game over scene. I’ve got this code which isnt working, but no errors:

using UnityEngine;
using System.Collections;

public class fading : MonoBehaviour {

public Texture2D fadeOutTexture; //image that overlays screen
public float fadeSpeed = 0.8f; //fade speed

private int drawDepth = -1000; //textures order in hierarchy
private float alpha = 1.0f; //textures alpha value
private int fadeDir = -1; //-1 fade in, 1 fade out

void onGUI () {

	alpha += fadeDir * fadeSpeed * Time.deltaTime;
	alpha = Mathf.Clamp01(alpha);
	GUI.color = new Color (GUI.color.g, GUI.color.b, alpha);
	GUI.depth = drawDepth; 
	GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture); }

public float BeginFade (int direction) {
	fadeDir = direction;
	return (fadeSpeed);	}

void onLevelWasLoaded() {
	BeginFade (-1);

}

}

Then attached to a gameObect in the game scene:

IEnumerator sceneChange() {
		float fadeTime = GameObject.Find ("destroyer").GetComponent<fading>().BeginFade(1);
		yield return new WaitForSeconds(fadeTime);
		Application.LoadLevel("startScene");
	}



	void OnCollisionEnter2D (Collision2D col) {

		if (col.gameObject.tag == "enemyPlanet") {

			Destroy (gameObject);
			sceneChange();
		}
	}

What am I doing wrong??

First, your calling a coroutine as a simple method, you need to use the StartCoroutine method,

Change this:

sceneChange();

to this:

StartCoroutine(sceneChange());

Second, LoadLevel is synchronous, it loads the whole new scene before returning control to Unity (I think it waits until the end of the current frame though). Once it finishes Unity destroys every object, creates the new scene and then starts calling the Awake methods.

Any coroutine started before that will stop since the objects that started them where destroyed. Your “fading” script won’t exists once the new level is loaded.

Maybe you need to look at LoadLevelAsync or LoadLevelAdditive for this.