0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】Scene.buildIndexが-1になるのはDontDestroyOnLoadなScene

Last updated at Posted at 2019-12-13

問題

スクリプトで生成されるGameObjectは、生成したSceneを破棄する時にまとめて破棄されてほしいので、SceneManager.MoveGameObjectToScene(obj, SceneManager.GetSceneByBuildIndex(buildIndex)); として管理していたが、以下のエラーが出ることがあった。

Console.
ArgumentException: GetSceneByBuildIndex: Invalid build index: -1
To add a scene to the build settings use the menu File->Build Settings...

調べてみると、DontDestroyOnLoad()としたGameObjectのsceneはbuildIndexが-1になる様子。

解決方法

buildIndexが負の場合は DontDestroyOnLoad()SceneManager.MoveGameObjectToScene() の代わりに実行すればいいのだが、以下のように、sceneを丸ごと SceneManager.MoveGameObjectToScene() に渡しても大丈夫だった。

buildIndexTest.cs
private void Awake()
{
    Object.DontDestroyOnLoad(gameObject);
}

private void Start () {
    var obj = new GameObject();
    Debug.Log(obj.scene.buildIndex);

    // buildIndexを経由すると以下のエラーになる
    // ArgumentException: GetSceneByBuildIndex: Invalid build index: -1
    // To add a scene to the build settings use the menu File->Build Settings...
    //var scene = SceneManager.GetSceneByBuildIndex(gameObject.scene.buildIndex);
    //SceneManager.MoveGameObjectToScene(obj, scene);
    //Debug.Log(obj.scene.buildIndex);

    SceneManager.MoveGameObjectToScene(obj, gameObject.scene);
    Debug.Log(obj.scene.buildIndex);
}
Console.
1
UnityEngine.Debug:Log(Object)

-1
UnityEngine.Debug:Log(Object)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?