(Re)Generate run-time objects in Unity Editor mode
A 2 minutes story written on Aug 2014 by Adrian B.G.
Testing the Medium editor and my first post about Unity Game Engine.
Problem
You have a script that generates something (ex a grid tile, a set of flying elves or goblin space shuttles) at run-time. Usually you write code, save, run the project, , see the results .. <repeat process>. You can take a shortcut and run code in editor too, saving time and energy.
Solution
Use [ExecuteInEditMode] You should read the documentation first http://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
Usually I want my code to be executed manually (not at every Update()) so I will use a trigger (a public bool variable) that will tell the script to execute when I’m ready (see C# example).
using UnityEngine;
......
[**ExecuteInEditMode**]
public class TileGenerator : MonoBehaviour {``.......``public bool **restartLevel** = false;``void Start () {
this.restartLevel = true;
}
// Update is called once per frame
void Update () {
//this is how you can run specific code
if ( Application.isEditor){
InitPrefabs();
}
if ( **restartLevel** ){
restartLevel = false;
this.GenerateLevel();
}
}``/// <summary>
/// Draws all the tiles from this level and remove the old ones.
/// </summary>
void GenerateLevel(){
.....magic code....
}
The variable must be public in order to control it’s state from an Inspector. Usually I make a special tiny Inspector window, locked, in a screen corner, so I can easily regenerate the current level / scene.
Pro advice: You can assign a custom key for this operation see Unity Doc — MenuItem ( like ctrl+r ) if you prefer the keyboard.
Image from ode2308