[unity] 선택한 파일 Scene으로 가져오는법.
public class ImportFilesIntoScene : EditorWindow
{
[MenuItem("Window/Import Files into Scene")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(ImportFilesIntoScene));
}
private void OnGUI()
{
GUILayout.Label("Selected Files to Import:", EditorStyles.boldLabel);
foreach (Object obj in Selection.objects)
{
EditorGUILayout.ObjectField(obj, typeof(GameObject), true);
}
if (GUILayout.Button("Import Selected Files"))
{
ImportSelectedFiles();
}
}
private void ImportSelectedFiles()
{
foreach (Object obj in Selection.objects)
{
GameObject prefab = obj as GameObject;
if (prefab != null)
{
Instantiate(prefab);
}
}
}
}
위 예제는 커스텀 윈도우에 선택된 항목(프로젝트창 파일 또는 하이어러키창의 오브젝트)을 보여주고 버튼을 누를 시 선택된 항목을 인스턴스화 한것이다.
간단하게 설명하면 Selection 은 선택된 항목 리스트를 담고있는 기능을 한다.
이 셀렉션 오브젝트를 for문을 돌면서 이게 게임오브젝트형태라면 인스턴스화 하는 건데 내가 필요한건 하이어러키 창의 오브젝트들을 인스턴스화 할 필요는 없었다.
bool isInProjectWindow = EditorUtility.IsPersistent(obj);
이걸 이용한다면 선택된 오브젝트가 프로젝트 창에 있는것인지 확인이 가능하다.
>참조
https://docs.unity3d.com/ScriptReference/EditorUtility.IsPersistent.html
Unity - Scripting API: EditorUtility.IsPersistent
Typically assets like Prefabs, textures, audio clips, animation clips, materials are stored on disk. Returns false if the object lives in the Scene. Typically this is a game object or component but it could also be a material that was created from code and
docs.unity3d.com
그리고 보통 프로젝트 창에 있는 에셋을 직접 드래그 한것처럼 프리팹에 대한 연결이 있는채로 인스턴스화 하고 싶다면
Instantiate 대신 PrefabUtility.InstantiatePrefab(prefab); 을 사용하면 된다.
https://docs.unity3d.com/ScriptReference/PrefabUtility.InstantiatePrefab.html
Unity - Scripting API: PrefabUtility.InstantiatePrefab
This is similar to Instantiate but creates a Prefab connection to the Prefab. If you do not specify a Scene handle, the Prefab is instantiated in the active Scene. Note: You should not instantiate Prefabs from the OnValidate() or Awake() method. This is be
docs.unity3d.com