I’m coding an editor extension that will create a “first person controller” in just a few seconds through a graphical interface (no need for coding), to speed the workflow up, both for me, and for others who might think this is usefull aswell. I’ve created a system for creating the visible stuff (collider, camera etc.), but it also need to create a script, add some lines of code to it, save it and apply it to the object (which I hope is possible)!
formatting is less than ideal to reduce the number of lines posted, but it’s still readable.
using UnityEngine;
using UnityEditor;
using System.IO;
public class CodeGenerator : EditorWindow
{
[MenuItem("Answers/CodeGenerator", false, 1000)]
public static void CodeGen() { GetWindow<CodeGenerator>(); }
private string _assetsFolder, _scriptsFolder, _scriptName;
void OnEnable()
{
if (string.IsNullOrEmpty(_assetsFolder)) _assetsFolder = Directory.GetCurrentDirectory() + @"/Assets/";
if (string.IsNullOrEmpty(_scriptsFolder)) _scriptsFolder = _assetsFolder + @"Scripts/";
if (!File.Exists(_scriptsFolder)) Directory.CreateDirectory(_scriptsFolder);
if (string.IsNullOrEmpty(_scriptName)) _scriptName = @"GeneratedScript";
}
void OnGUI()
{
EditorGUILayout.BeginHorizontal();
_scriptName = EditorGUILayout.TextField(@"Filename:", _scriptName);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(@"Gen Code")) GenerateCode();
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(@"Compiling: ", EditorApplication.isCompiling ? @"Yes" : @"No");
EditorGUILayout.EndHorizontal();
}
void Update() { if (EditorApplication.isCompiling) EditorApplication.isPlaying = false; }
void GenerateCode()
{
var scriptFilename = _scriptsFolder + _scriptName + @".cs";
var script = string.Format("using UnityEngine;
public class {0} : MonoBehaviour
{{}}
", _scriptName);
File.WriteAllText(scriptFilename, script);
AssetDatabase.Refresh(); // Force recompile - can be SLOW…
}
}