I am trying to make a menu item to generate scripts. I want this item to show in the “Add Component” menu for game objects. The goal is for the menu item to ask for a string “input_text” and generate a script with that name. Then, the script is attached to the game object it was called on if the function was called from the “Add Component” menu.
using System.IO;
using UnityEditor;
using UnityEngine;
public class ScriptBundle : EditorWindow{
private string input_text = "";
[MenuItem("Component/Custom Items/Script and Editor")]
public static void ShowWindow(){
ScriptBundle win = GetWindow<ScriptBundle>("Script + Editor Generator");
win.minSize = new Vector2(400,100);
win.maxSize = new Vector2(400,100);
win.position = new Rect(Screen.width/2, Screen.height/2, 400, 100);
}
private void OnEnable(){
this.minSize = new Vector2(400,100);
this.maxSize = new Vector2(400,100);
this.position = new Rect(Screen.width/2, Screen.height/2, 400, 100);
}
private void OnGUI(){
GUILayout.Label("Generate a script and its inspector editor script", EditorStyles.boldLabel);
input_text = EditorGUILayout.TextField("Script Name: ", input_text);
GUILayout.Space(10);
if (GUILayout.Button("Generate")){
Debug.Log(input_text);
GenerateScript(input_text);
attachScriptToGameobject(input_text);
Close();
}
}
private void GenerateScript(string input_text){
Debug.Log("Generate");
string path = $"Assets/{input_text}.cs";
if (File.Exists(path)){
Debug.LogError("A script with this name already exists.");
}
string template = "using UnityEngine;\n\npublic class " + input_text + " : MonoBehaviour\n{\n\n}";
try{
//File.WriteAllText(path,template);
}catch(Exception ex){
Debug.Log($"Faild to write: {ex}")
}
AssetDatabase.Refresh();
}
private void attachScriptToGameobject(string input_text){
Gameobject selected = Selection.activeGameObject;
Debug.log(selected.transform.name);
if (selected != null){
selected.AddComponent(System.Type.GetType(input_text));
Debug.Log("Script Attached");
}
}
}
Notice how the line for writing the template to the script is commented. This line causes issues when it is executed. None of the Debug.Logs run be them before or after the WriteAllText. Also, the code won’t recognize the activeGameobject at all and hence won’t attach the script to it.
What could be the problem, and how can I fix it?