- Home /
Adding GameObject to selected Scene
I am trying to create a window, from where a user can add gameobjects(prefab) to a scene by the click of a button. The problem I am facing is that the gameobject is added to the first scene always, not to the scene I have selected. I am new to unity, any help would be highly appreciated.
Following is my code:
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using UnityEngine.UI;
using System.IO;
public class ToolBox : EditorWindow
{
[MenuItem("Window/Tool Box")]
public static void ShowWindow()
{
GetWindow<ToolBox>("Tool Box");
}
void OnGUI()
{
if(GUILayout.Button("Button")){
//EditorUtility.SaveWindowLayout("Assets/Editor/Layouts/Customizer Layout.dwlt");
Object prefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/buttonPrefab.prefab", typeof(GameObject));
GameObject _prefab = Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
_prefab.transform.SetParent (GameObject.Find("Canvas").GetComponent<RectTransform>(), false);
}
if(GUILayout.Button("Text")){
Object prefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/textPrefab.prefab", typeof(GameObject));
GameObject _prefab = Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
_prefab.transform.SetParent (GameObject.Find("Canvas").GetComponent<RectTransform>(), false);
}
}
}
Answer by revolute · Oct 30, 2019 at 10:49 AM
Set your scene to active before instantiating.
SceneManager.SetActiveScene(targetScene);
will set the current active scene so that the next gameobjects will be created in the targeted scene.
Use SceneManager.sceneCount
to get current scene count and iterate through them by SceneManager.GetSceneAt
.
I have another window where the user adds the scenes, as the scene name is not fixed, I cannot access the scene through its name.
Hence the scene count comes in and you dont need to know what scenes are loaded. They are give an index and you can retrieve them by GetSceneAt(number). Scene objects hold scene names to use in the window.