Enable gameobjects on active scene only

I have 3 scenes which load at the same time:

  • Scene1
  • Scene2
  • Scene3 ← current active scene

I want it when I set scene2 to active, all gameobjects in scene 2 will be enabled and the rest gameobjects in scene1 and scene3 will be deactived.

Can I do that? If yes, please help me

Maybe you can take a look at SceneManager.activeSceneChanged and Scene.GetRootGameObjects.

Here is an example:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MySceneManager : MonoBehaviour
{
    public void Start()
    {
        SceneManager.activeSceneChanged += OnActiveSceneChanged;

        ToggleSceneObjects();
    }


    public void OnDestroy()
    {
        SceneManager.activeSceneChanged -= OnActiveSceneChanged;
    }


    private void OnActiveSceneChanged(Scene scene1, Scene scene2)
    {
        ToggleSceneObjects();
    }


    private void ToggleSceneObjects()
    {
        Scene activeScene = SceneManager.GetActiveScene();

        for (int i = 0; i < SceneManager.sceneCount; i++)
        {
            Scene scene = SceneManager.GetSceneAt(i);

            GameObject[] rootGameObjects = scene.GetRootGameObjects();

            foreach (var obj in rootGameObjects)
            {
                if (scene != activeScene)
                {
                    obj.SetActive(false);
                }
                else
                {
                    obj.SetActive(true);
                }
            }
        }
    }
}