Skip to content

Instantly share code, notes, and snippets.

@am1tanaka
Last active September 6, 2022 09:42
Show Gist options
  • Select an option

  • Save am1tanaka/eff6d5d29d44c06005a3eb7a62b2e062 to your computer and use it in GitHub Desktop.

Select an option

Save am1tanaka/eff6d5d29d44c06005a3eb7a62b2e062 to your computer and use it in GitHub Desktop.
新規シーンを作成して指定のフォルダーに保存するエディタ拡張サンプルコード
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEditor.SceneManagement;
using System.IO;
public class NewSceneEditorWindow : EditorWindow
{
TextField sceneNameText;
Button createButton;
[MenuItem("Tools/AM1/Create New Scene")]
public static void ShowNewSceneWindow()
{
NewSceneEditorWindow wnd = GetWindow<NewSceneEditorWindow>();
wnd.titleContent = new GUIContent("NewSceneEditorWindow");
}
public void CreateGUI()
{
// Each editor window contains a root VisualElement object
VisualElement root = rootVisualElement;
// Import UXML
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/NewSceneEditorWindow.uxml");
VisualElement labelFromUXML = visualTree.Instantiate();
root.Add(labelFromUXML);
// コントロールのインスタンスを取得
sceneNameText = root.Query<TextField>("SceneName").First();
createButton = root.Query<Button>("CreateButton").First();
// コントロールの状態を更新
UpdateControl(null);
// 処理を登録
sceneNameText.RegisterCallback<InputEvent>(UpdateControl);
createButton.RegisterCallback<ClickEvent>(CreateScene);
}
/// <summary>
/// コントロールの状態を更新。
/// </summary>
void UpdateControl(InputEvent ievt)
{
createButton.SetEnabled(!string.IsNullOrEmpty(sceneNameText.text));
}
/// <summary>
/// 新規シーンの作成
/// </summary>
void CreateScene(ClickEvent cevt)
{
// フォルダー選択
string folder = EditorUtility.SaveFolderPanel("保存先フォルダー", "", "");
if (string.IsNullOrEmpty(folder)) return;
createButton.SetEnabled(false);
// 新しいシーンを作成
var newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
// オブジェクト作成
var go = new GameObject();
go.name = sceneNameText.text + "Behaviour";
Undo.RegisterCreatedObjectUndo(go, $"Created {go.name} Object.");
// シーンの保存
string scenePath = Path.Combine(folder, sceneNameText.text + ".unity");
var relPath = "Assets/" + Path.GetRelativePath(Application.dataPath, scenePath);
var path = AssetDatabase.GenerateUniqueAssetPath(relPath);
EditorSceneManager.SaveScene(newScene, path);
AssetDatabase.Refresh();
sceneNameText.value = "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment