How to make a scene reload but with a different background color?

Hey! I have a trigger set up that reloads the scene, but I want it to reload with a different background color (vibrant, not too dark, hence the ColorHSV) Here’s what I got:

public Camera cam;

    public void LoadNextLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        cam.backgroundColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
    }

The scene changes color, but after a split second the scene reloads and the color goes back to normal. How do I fix this?

Thanks!!

Would it be an option for your background to set the random color on start by itself? Then the color would set up every time you load the scene. That means that your camera will have a script attached that on start will assign the random color.

However, if you want to persist the object though reloads (eg cause your first color cannot be random) you can set DontDestroyOnLoad on your camera. In this scenario, every time you reload the scene you will get the duplicate of the camera. A more robust way of doing this would be implementing the Singleton Pattern. This will cause you to keep the object with the component attached to it no matter the reloads and the would be duplicates will get destroyed.

The idea behind the solution below is that you have an SceneLoader/GameManager object that doesn’t get destroyed or reloaded between scenes. This allows you to call an action when the screen is loaded.

public Camera cam;

void Awake () {
	// Prevents this object to be destroyed on scene change
	DontDestroyOnLoad(this.gameObject);
}

// This will run on the first screen
void Start () {
	// Initialize is called at the start of each load
	Initialize ();
	
	// Add the initialize function to the screen loader
	// Meaning it will run when a scene is loaded
	SceneManager.sceneLoaded += Initialize;
}

void Initialize () {
	cam = Camera.Main;
	cam.backgroundColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
}


/* This just adds and removes the Initialize function when this object is disable or enabled
 * Only necessary when enabling or disable this script 
 */
void OnEnable() {
	SceneManager.sceneLoaded += OnLevelFinishedLoading;
}

void OnDisable() {
	SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}