简体   繁体   中英

Unity create scenes and add content to it in the editor

What I want to do:

  1. I have a list of Sector gameObjects on my scene
  2. I want to iterate through and create a new scene for it, scene_sector_xxx
  3. the scene's content will be the gameObject only at that position
  4. add this scene to runtime

Why I want this?

I need to create an async/additive scene loader at runtime to speed up everything. When the player is near by a sector then just want to load that sector piece immediatelly.

Is it possible? In editor maybe?

Update: my code:

    private static IEnumerator SaveSectorToSceneCoroutine(Sector sector)
    {
        
        //TODO save this go to a new scene
        var go = Object.Instantiate(sector.gameObject);
        //Object.DontDestroyOnLoad(go); //this is not working from editor
        //or need a prefab?

      

        var newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); //maybe better from calling this in the background, how?
        SceneManager.MoveGameObjectToScene(go, newScene); //this not working, "go" became null

     

        string[] path = EditorSceneManager.GetActiveScene().path.Split(char.Parse("/"));
        path[path.Length - 1] = "_SCN_SECTOR_" + go.name + path[path.Length - 1];
        EditorSceneManager.SaveScene(newScene, string.Join("/", path), true);
      
        Debug.Log("Saved Scene " + path);   
    }

   

Your issue is probably in EditorSceneManager.NewScene .

As mode you are passing in NewSceneMode.Single

All current open Scenes are closed and the newly created Scene are opened.

What you rather want to use is NewSceneMode.Additive

The newly created Scene is added to the current open Scenes.

like eg

var go = Object.Instantiate(sector.gameObject);

var newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); 

SceneManager.MoveGameObjectToScene(go, newScene); 

string[] path = EditorSceneManager.GetActiveScene().path.Split('//'));
path[path.Length - 1] = "_SCN_SECTOR_" + go.name + path[path.Length - 1];
EditorSceneManager.SaveScene(newScene, string.Join('//', path), true);

EditorSceneManager.CloseScene(newScene, true);
  
Debug.Log("Saved Scene " + path);   

Then I don't think this should be a Coroutine. I don't see any need for/use of doing

yield return null;

in this use case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM