Runtime Editor Docs
Overview
Runtime Editor is the set of scripts and prefabs which help you to create scene editor, game level editor or build your own modeling application. It supports drag & drop, undo & redo and selection api. To implement user interface and core functions runtime editor use transform-handles, gizmos, save load subsystem and three controls: menu, virtualizing tree view and dock panels. Out of the box it has seven Views:
- Scene View to manipulate objects in the scene.
- Hierarchy View to display and manipulate object tree.
- Project View to manage assets and scenes.
- Inspector View to display and edit object properties.
- Console View to display information, warnings and errors.
- Game View main game camera output.
- Animation View to create and edit the runtime animations.
- Add More...
The Runtime Editor has many ready-to-use property and component editors and it is relatively easy to create new ones. "Add Component" drop-down button allows you to add components at runtime. There are also several important dialogs included:
- Save Scene Dialog.
- Object Picker.
- Color Picker.
- Asset Bundles and Libraries Importer.
- Manage Projects Dialog.
Getting Started
To get started with Runtime Editor do following:
- Create new scene and save it.
-
Click Tools->Runtime Editor->Create
-
Add Battlehub/RTEditor/Scripts/Game View Camera component to Main Camera
-
Create several Game Objects and add Expose To Editor component.
-
Click Tools->Runtime SaveLoad->Config->Build All
-
Hit Play
Few more steps:
- Create Asset Library
-
Launch runtime editor and click File->Import Assets.
-
Select the built-in asset library created in step 1.
-
Import assets.
-
You will see the imported assets in the project window.
Note
Demo scene can be found in Assets/Battlehub/RTEditorDemo/Content/Runtime/RTEditor
Main & Context Menu
Runtime Editor use Menu control to implement main and context-menu. To extend main menu create static class with [MenuDefinition] attribute and add static methods with [MenuCommand] attribute.
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using Battlehub.UIControls.MenuControl;
using UnityEngine;
[MenuDefinition]
public static class MyMenu
{
/// add new command to exising menu
[MenuCommand("MenuWindow/Create My Window")]
public static void CreateMyWindow()
{
Debug.Log("Create My Window");
}
/// add new command to new menu
[MenuCommand("My Menu/My Submenu/My Command")]
public static void CreateMyMenu()
{
Debug.Log("Create My Menu");
}
/// disable menu item
[MenuCommand("My Menu/My Submenu/My Command", validate: true)]
public static bool ValidateMyCommand()
{
Debug.Log("Disable My Command");
return false;
}
/// replace existing menu item
[MenuCommand("MenuFile/Close")]
public static void Close()
{
Debug.Log("Intercepted");
IRuntimeEditor rte = IOC.Resolve<IRuntimeEditor>();
rte.Close();
}
/// Hide existing menu item
[MenuCommand("MenuHelp/About RTE", hide: true)]
public static void HideAbout() { }
}
To open context menu with custom commands do following:
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using Battlehub.UIControls.MenuControl;
using UnityEngine;
public static class MyContextMenu
{
public static void OpenContextMenu()
{
IContextMenu contextMenu = IOC.Resolve<IContextMenu>();
MenuItemInfo cmd1 = new MenuItemInfo { Path = "My Command 1" };
cmd1.Action = new MenuItemEvent();
cmd1.Action.AddListener((args) =>
{
Debug.Log("Run My Command1");
IRuntimeEditor editor = IOC.Resolve<IRuntimeEditor>();
Debug.Log(editor.Selection.activeGameObject);
});
MenuItemInfo cmd2 = new MenuItemInfo { Path = "My Command 2" };
cmd2.Validate = new MenuItemValidationEvent();
cmd2.Action = new MenuItemEvent();
cmd2.Validate.AddListener((args) =>
{
args.IsValid = false;
});
cmd2.Action.AddListener((args) =>
{
Debug.Log("Run My Command2");
});
contextMenu.Open(new[]
{
cmd1, cmd2
});
}
}
Built-in context menu populated and opened from Assets/Battlehub/RTEditor/Runtime/RTEditor/ProjectFolderViewImp.cs and ProjectTreeViewImpl.cs
RTEDeps
The main purpose of the Assets/Battlehub/RTEditor/Runtime/RTEditor/RTEDeps.cs class is to register various services into IOC:
- IResourcePreviewUtility - create preview for Game Object or asset.
- IWindowManager - manage build-in and custom windows.
- IContextMenu - create and show context menu.
- IRuntimeConsole - log messages cache.
- IRuntimeEditor - the main interface of the RuntimeEditor.
IRuntimeEditor
IRuntimeEditor inherits the IRTE interface and adds several important methods and events.
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using UnityEngine;
public class GetRuntimeEditor : MonoBehaviour
{
void Start()
{
IRuntimeEditor editor = IOC.Resolve<IRuntimeEditor>();
}
}
Events:
event RTEEvent SceneLoading
- fired before loading the scene.event RTEEvent SceneLoaded
- fired after loading the scene.event RTEEvent SceneSaving
- fired before saving the scene.event RTEEvent SceneSaved
- fired before saving the scene.
Methods:
void NewScene(bool confirm = true)
- create a new scene (show the confirmation dialog by default).-
void SaveScene()
- save the current scene. If the scene is new, the save scene dialog will appear. -
void CreateWindow(string window)
- call corresponding method of window manager. -
void CreateOrActivateWindow(string window)
- this method creates a window only if it does not exist. -
ProjectAsyncOperation<AssetItem[]> CreatePrefab(ProjectItem folder, ExposeToEditor obj, bool? includeDeps = null)
- create prefab with preview. ProjectAsyncOperation<AssetItem[]> SaveAssets(UnityObject[], Action<AssetItem[]>)
- save assets.ProjectAsyncOperation<ProjectItem[]> DeleteAssets(ProjectItem[] projectItems)
- delete assets.ProjectAsyncOperation<AssetItem> UpdatePreview(UnityObject obj)
- update asset preview.
Example:
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using Battlehub.RTSL.Interface;
using System.Collections;
using UnityEngine;
public class IRuntimeEditorMethodsUsageExample : MonoBehaviour
{
IEnumerator Start()
{
//Get runtime editor
IRuntimeEditor editor = IOC.Resolve<IRuntimeEditor>();
//Use IProject interface if editor is not opened or does not exist.
//See save-load/#project for details
Debug.Assert(editor.IsOpened);
//Create Prefabs folder
IProject project = IOC.Resolve<IProject>();
yield return project.CreateFolder("Prefabs");
ProjectItem folder = project.GetFolder("Prefabs");
//Create new object and hide it from hierarchy
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.hideFlags = HideFlags.HideAndDontSave;
go.SetActive(false);
//Create prefab with preview and destroy source object
yield return editor.CreatePrefab(folder, go.AddComponent<ExposeToEditor>(), true);
Destroy(go);
//Load prefab
ProjectAsyncOperation<Object[]> load = project.Load<GameObject>("Prefabs/Sphere");
yield return load;
GameObject loadedGO = load.Result[0] as GameObject;
//... Make changes
//Update preview
yield return editor.UpdatePreview(loadedGO);
//Save changes
yield return editor.SaveAssets(new[] { loadedGO });
//Get corresponding project item
ProjectItem projectItem = project.Get<GameObject>("Prefabs/Sphere");
//Delete prefab and clear undo stack
yield return editor.DeleteAssets(new[] { projectItem });
}
}
Window Manager
Window Manager allows you to create complex windows, such as an inspector or scene, and simple dialogs, such as a message box or confirmation. The difference between dialog and window is rather subtle. The content of the dialog can be anything, and it can not be docked. To be considered as a window or dialog window, a Runtime Window component must be attached to the game object. When the runtime window is activated, the other windows are deactivated. The dialog cannot deactivate the window.
Note
Default windows and dialogs can be found in Assets/Battlehub/RTEditor/Content/Runtime/RTEditor/Prefabs
Note
Window Manager use dock panels control.
Get window manager:
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using UnityEngine;
public class GetWindowManager : MonoBehaviour
{
void Start()
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
}
}
Show message box:
wm.MessageBox("Header", "Text", (sender, args) =>
{
Debug.Log("OK Click");
});
Show confirmation:
wm.Confirmation("Header", "Text",
(sender, args) =>
{
Debug.Log("Yes click");
},
(sender, args) =>
{
Debug.Log("No click");
},
"Yes", "No");
Activate window:
wm.ActivateWindow(RuntimeWindowType.Scene.ToString());
Create window:
wm.CreateWindow(RuntimeWindowType.Scene.ToString());
Create dialog window:
IWindowManager wm = IOC.Resolve<IWindowManager>();
wm.CreateDialogWindow(RuntimeWindowType.About.ToString(), "Header",
(sender, args) => { Debug.Log("OK"); },
(sender, args) => { Debug.Log("Cancel"); });
Set default layout:
IWindowManager wm = IOC.Resolve<IWindowManager>();
string persistentLayoutName = wm.DefaultPersistentLayoutName;
if (wm.LayoutExist(persistentLayoutName))
{
wm.DeleteLayout(persistentLayoutName);
}
wm.SetDefaultLayout();
How to: add custom window to Window Manager
Note
For information on how to create custom window please navigate to this -> this <- section
- Create class derived from Runtime Window
- Duplicate Assets/Battlehub/RTEditor/Content/Runtime/RTEditor/Prefabs/Views/Resources/
TemplateWindow.prefab. - Add CustomWindow component created in step 1.
-
Set
Window Type
to Custom. -
Create registration script and add it to game object in the scene.
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using Battlehub.UIControls.MenuControl;
using UnityEngine;
[MenuDefinition]
public class RegisterCustomWindows : EditorExtension
{
protected override void OnEditorExist()
{
base.OnEditorExist();
RegisterWindows();
}
private void RegisterWindows()
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
wm.RegisterWindow(new CustomWindowDescriptor
{
IsDialog = false,
TypeName = "MyWindow",
Descriptor = new WindowDescriptor
{
Header = "My Window",
MaxWindows = 1,
Icon = Resources.Load<Sprite>("IconNew"),
ContentPrefab = Resources.Load<GameObject>("CustomWindow")
}
});
}
[MenuCommand("MenuWindow/CustomWindow")]
public static void ShowCustomWindow()
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
wm.CreateWindow("MyWindow");
}
}
Note
Alternatively you can use Tools->Runtime Editor->Custom Window menu to create prefab, window script and registration script.
How to: override default layout
To override default layout do following:
- Create a LayoutOverride script.
- Modify
DefaultLayout
method. - Create a new game object and add LayoutOverride component.
- To prevent the game object from being destroyed by Save & Load add RTSLIgnore component.
using Battlehub.RTCommon;
using Battlehub.UIControls.DockPanels;
using Battlehub.RTEditor;
using UnityEngine;
public class LayoutOverride : EditorExtension
{
protected override void OnEditorCreated(object obj)
{
OverrideDefaultLayout();
}
protected override void OnEditorExist()
{
OverrideDefaultLayout();
IRuntimeEditor editor = IOC.Resolve<IRuntimeEditor>();
if (editor.IsOpened)
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
wm.SetLayout(DefaultLayout, RuntimeWindowType.Scene.ToString());
}
}
private void OverrideDefaultLayout()
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
wm.OverrideDefaultLayout(DefaultLayout, RuntimeWindowType.Scene.ToString());
}
static LayoutInfo DefaultLayout(IWindowManager wm)
{
bool isDialog;
WindowDescriptor sceneWd;
GameObject sceneContent;
wm.CreateWindow(RuntimeWindowType.Scene.ToString(), out sceneWd, out sceneContent, out isDialog);
WindowDescriptor gameWd;
GameObject gameContent;
wm.CreateWindow(RuntimeWindowType.Game.ToString(), out gameWd, out gameContent, out isDialog);
WindowDescriptor inspectorWd;
GameObject inspectorContent;
wm.CreateWindow(RuntimeWindowType.Inspector.ToString(), out inspectorWd, out inspectorContent, out isDialog);
WindowDescriptor hierarchyWd;
GameObject hierarchyContent;
wm.CreateWindow(RuntimeWindowType.Hierarchy.ToString(), out hierarchyWd, out hierarchyContent, out isDialog);
LayoutInfo layout = new LayoutInfo(false,
new LayoutInfo(
wm.CreateLayoutInfo(sceneContent.transform, sceneWd.Header, sceneWd.Icon),
wm.CreateLayoutInfo(gameContent.transform, gameWd.Header, gameWd.Icon)),
new LayoutInfo(true,
wm.CreateLayoutInfo(inspectorContent.transform, inspectorWd.Header, inspectorWd.Icon),
wm.CreateLayoutInfo(hierarchyContent.transform, hierarchyWd.Header, hierarchyWd.Icon),
0.5f),
0.75f);
return layout;
}
}
You should see following:
How to: override scene parameters
To override scene parameters do following:
- Create SceneParametersOverride script.
- Implement
OnAfterLayout
event handler. - Create game object and add SceneParametersOverride component.
- To prevent the game object from being destroyed by Save & Load add RTSLIgnore component.
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using Battlehub.RTHandles;
using Battlehub.UIControls.DockPanels;
using UnityEngine;
public class SceneParametersOverride: EditorExtension
{
private IWindowManager m_wm;
protected override void OnEditorExist()
{
m_wm = IOC.Resolve<IWindowManager>();
m_wm.AfterLayout += OnAfterLayout;
m_wm.WindowCreated += OnWindowCreated;
}
protected override void OnEditorClosed()
{
base.OnEditorClosed();
if(m_wm != null)
{
m_wm.AfterLayout -= OnAfterLayout;
m_wm.WindowCreated -= OnWindowCreated;
}
}
protected override void OnDestroy()
{
base.OnDestroy();
if (m_wm != null)
{
m_wm.AfterLayout -= OnAfterLayout;
m_wm.WindowCreated -= OnWindowCreated;
}
}
private void OnWindowCreated(Transform window)
{
SetupScene(window);
}
private void OnAfterLayout(IWindowManager wm)
{
Transform[] windows = wm.GetWindows(RuntimeWindowType.Scene.ToString());
for(int i = 0; i < windows.Length; ++i)
{
SetupScene(windows[i]);
}
}
private void SetupScene(Transform w)
{
RuntimeWindow window = w.GetComponent<RuntimeWindow>();
if(window == null)
{
return;
}
IRuntimeSceneComponent scene = window.IOCContainer.Resolve<IRuntimeSceneComponent>();
if(scene == null)
{
return;
}
scene.Pivot = new Vector3(5, 0, 0);
scene.CameraPosition = Vector3.right * 20;
scene.IsOrthographic = true;
scene.PositionHandle.GridSize = 2;
scene.RotationHandle.GridSize = 5;
scene.SizeOfGrid = 2;
scene.IsScaleHandleEnabled = false;
scene.IsSceneGizmoEnabled = true;
scene.IsBoxSelectionEnabled = false;
scene.CanSelect = true;
scene.CanSelectAll = true;
scene.CanRotate = true;
scene.CanPan = false;
scene.CanZoom = true;
Tab tab = Region.FindTab(window.transform);
tab.CanClose = false;
}
}
How to: override tools panel
To override tools panel do following:
- Create ToolsPanelOverride script.
- Create game object and add ToolsPanelOverride component.
- Set Tools Prefab field
- To prevent the game object from being destroyed by Save & Load add RTSLIgnore component.
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using UnityEngine;
public class ToolsPanelOverrideExample : EditorExtension
{
[SerializeField]
private Transform m_toolsPrefab = null;
protected override void OnEditorCreated(object obj)
{
OverrideTools();
}
protected override void OnEditorExist()
{
OverrideTools();
IRuntimeEditor editor = IOC.Resolve<IRuntimeEditor>();
if (editor.IsOpened)
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
if (m_toolsPrefab != null)
{
wm.SetTools(Instantiate(m_toolsPrefab));
}
else
{
wm.SetTools(null);
}
}
}
private void OverrideTools()
{
IWindowManager wm = IOC.Resolve<IWindowManager>();
wm.OverrideTools(m_toolsPrefab);
}
}
You should see following:
How to: override ui scale
To override ui scale do following:
- Create UIScaleOverride script.
- Create game object and add UIScaleOverride component.
- Set desired
Scale
- To prevent the game object from being destroyed by Save & Load add RTSLIgnore component.
using Battlehub.RTCommon;
using Battlehub.RTEditor;
using UnityEngine;
public class UIScaleOverride : EditorExtension
{
[SerializeField]
private float Scale = 2;
protected override void OnEditorExist()
{
ISettingsComponent settings = IOC.Resolve<ISettingsComponent>();
settings.UIScale = Scale;
}
}
Before:
After:
How to: change runtime editor colors
RTE Appearance editor allows you to change colors of runtime editor. Reset Colors button will revert colors to default.
Following resources must be modified also:
To override ui colors programmatically do following:
- Create UIColorsOverride script.
- Create game object and add UIColorsOverride component.
- To prevent the game object from being destroyed by Save & Load add RTSLIgnore component.
using Battlehub.RTCommon;
using UnityEngine;
namespace Battlehub.RTEditor.Demo
{
public class UIColorsOverride : EditorExtension
{
protected override void OnEditorExist()
{
ISettingsComponent settings = IOC.Resolve<ISettingsComponent>();
settings.SelectedThemeIndex = -1;
RTEColors colors = new RTEColors();
colors.Primary = Color.red;
IRTEAppearance appearance = IOC.Resolve<IRTEAppearance>();
appearance.Colors = colors;
}
}
}
File Importers
File importers are used during file import procedure to convert external file format to format supported by Runtime Editor. For example .png images should be converted to UnityEngine.Texture2D before import. There are two build-in importers:
- PngImporter;
- FastObjImporter;
Built-in importers can be found in Assets\Battlehub\RTEditor\Runtime\RTEditor\Importers.
FileBrowser with importers can be opened using File->Import From File menu item
To write custom importer do following. Create new script and inherit your class from FileImporter:
using Battlehub.RTEditor;
using Battlehub.RTCommon;
using Battlehub.RTSL.Interface;
using System.Collections;
using System.IO;
using UnityEngine;
public class JpgImporterExample : FileImporter
{
public override string FileExt
{
get { return ".jpg"; }
}
public override string IconPath
{
get { return "Importers/Jpg"; }
}
public override IEnumerator Import(string filePath, string targetPath)
{
byte[] bytes = File.ReadAllBytes(filePath);
Texture2D texture = new Texture2D(4, 4);
if (texture.LoadImage(bytes, false))
{
IProject project = IOC.Resolve<IProject>();
IResourcePreviewUtility previewUtility = IOC.Resolve<IResourcePreviewUtility>();
byte[] preview = previewUtility.CreatePreviewData(texture);
yield return project.Save(targetPath, texture, preview);
}
else
{
Debug.LogError("Unable to load image " + filePath);
}
Object.Destroy(texture);
}
}
Note
Currently File Browser supported on Windows platform only
Inspector View
The main purpose of the inspector is to create different editors depending on the type of selected object and its components. Here is a general idea of what is happening:
- The user selects a Game Object, and the inspector creates a GameObject editor.
- The game object editor creates component editors.
- Each component editor creates property editors.
Prefabs:
- InspectorView can be found in Assets/Battlehub/RTEditor/Content/Runtime/RTEditor/
Prefabs/Views folder, - GameObject, Material and Component editors in Assets/Battlehub/RTEditor/Content/
Runtime/RTEditor/Prefabs/Editors, - Property editors in Assets/Battlehub/RTEditor/Content/Runtime/RTEditor/Prefabs/
Editors/PropertyEditors.
How To: Configure Editors
To select the editors to be used by the inspector, click Tools->Runtime Editor->Configuration
There are five sections in configuration window:
- Object Editors - select which editor to use for Game Object.
- Property Editors - select which editors to use for component properties.
- Material Editors - select which editors to use for materials
- Standard Component Editors – select which editors to use for standard components.
- Script Editors – select which editors to use for scripts.
After you select and enable the desired component editors, click the Save Editors Map button
How To: Select Component Properties
To select the properties displayed by the component editor, you need to create a class and inherit it from ComponentDescriptorBase<
using UnityEngine;
using System.Reflection;
using Battlehub.Utils;
using Battlehub.RTCommon;
namespace Battlehub.RTEditor
{
public class TransformComponentDescriptor : ComponentDescriptorBase<Transform>
{
public override object CreateConverter(ComponentEditor editor)
{
object[] converters = new object[editor.Components.Length];
Component[] components = editor.Components;
for (int i = 0; i < components.Length; ++i)
{
Transform transform = (Transform)components[i];
if (transform != null)
{
converters[i] = new TransformPropertyConverter
{
ExposeToEditor = transform.GetComponent<ExposeToEditor>()
};
}
}
return converters;
}
public override PropertyDescriptor[] GetProperties(ComponentEditor editor, object converter)
{
object[] converters = (object[])converter;
MemberInfo position = Strong.PropertyInfo((Transform x) => x.localPosition, "localPosition");
MemberInfo positionConverted = Strong.PropertyInfo((TransformPropertyConverter x) => x.LocalPosition, "LocalPosition");
MemberInfo rotation = Strong.PropertyInfo((Transform x) => x.localRotation, "localRotation");
MemberInfo rotationConverted = Strong.PropertyInfo((TransformPropertyConverter x) => x.LocalEuler, "LocalEulerAngles");
MemberInfo scale = Strong.PropertyInfo((Transform x) => x.localScale, "localScale");
MemberInfo scaleConverted = Strong.PropertyInfo((TransformPropertyConverter x) => x.LocalScale, "LocalScale");
return new[]
{
new PropertyDescriptor( "Position",converters, positionConverted, position),
new PropertyDescriptor( "Rotation", converters, rotationConverted, rotation),
new PropertyDescriptor( "Scale", converters, scaleConverted, scale)
};
}
}
}
TransformPropertyConverter is used to convert a quaternion to Euler angles. This is needed for Vector3Editor to be used instead of QuaternionEditor.
Note
The remaining built-in component descriptors are in the Assets/Battlehub/RTEditor/Runtime/RTEditor/Editors/ComponentDescriptors folder.
Resource Preview Utility
The Resource Preview utility is used to create a preview of objects. This is how to use it:
using Battlehub.RTCommon;
using UnityEngine;
using UnityEngine.UI;
namespace Battlehub.RTEditor.Demo
{
public class CreatePreviewExample : MonoBehaviour
{
[SerializeField]
private Image m_image = null;
[SerializeField]
private Object m_object = null;
private Texture2D m_previewTexture;
private Sprite m_previewSprite;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
IResourcePreviewUtility previewUtil = IOC.Resolve<IResourcePreviewUtility>();
if (m_previewTexture != null)
{
Destroy(m_previewTexture);
}
if (m_previewSprite != null)
{
Destroy(m_previewSprite);
}
if(previewUtil.CanCreatePreview(m_object))
{
m_previewTexture = previewUtil.CreatePreview(m_object);
m_previewSprite = Sprite.Create(m_previewTexture,
new Rect(0, 0, m_previewTexture.width, m_previewTexture.height),
new Vector2(0.5f, 0.5f));
m_image.sprite = m_previewSprite;
}
}
}
private void OnDestroy()
{
if (m_previewSprite != null)
{
Destroy(m_previewSprite);
}
if (m_previewTexture != null)
{
Destroy(m_previewTexture);
}
}
}
}