Skip to content

Instantly share code, notes, and snippets.

@GieziJo
Created February 19, 2020 12:28
Show Gist options
  • Save GieziJo/3081369e3600cd9816d4ddc79bd54f46 to your computer and use it in GitHub Desktop.
Save GieziJo/3081369e3600cd9816d4ddc79bd54f46 to your computer and use it in GitHub Desktop.
Create a new Script on a GameObject and start editing the file right away
// ===============================
// AUTHOR : J. Giezendanner
// CREATE DATE : 19.02.2020
// MODIFIED DATE :
// PURPOSE : Adds a context menu to create a new script on the selected GameObject, and opens the editor to
// edit the script
// SPECIAL NOTES : Inspired by http://answers.unity.com/answers/1007397/view.html
// ===============================
// Change History:
//==================================
using System;
using System.IO;
using UnityEngine;
using UnityEditor;
public static class ScriptHelper
{
[MenuItem("GameObject/Giezi's tools/Add Script and Edit", false, 0)]
static void AddRequiredScript()
{
if (Selection.activeGameObject != null)
{
GameObject go = Selection.activeGameObject;
// Ask for script creation location, set default location to "Assets/Scripts"
string assetPath = Application.dataPath + Path.DirectorySeparatorChar + "Scripts" + Path.DirectorySeparatorChar;
string path = EditorUtility.SaveFilePanel("Save new script", assetPath, "New Script","cs");
if (path.Length == 0)
return;
path = path.Replace(Application.dataPath + Path.AltDirectorySeparatorChar, "");
path = "Assets" + Path.AltDirectorySeparatorChar + path;
string name = Path.GetFileNameWithoutExtension(path);
string dir = Path.GetDirectoryName(path);
name = name.Replace(" ","_");
name = name.Replace("-","_");
name = name.Replace(".","_");
// Check if the class already exists
try
{
Activator.CreateInstance("Assembly-CSharp", name);
Debug.Log("A class with this name does already exist");
return;
}
catch (Exception e)
{}
// Create the class
string copyPath = dir + Path.DirectorySeparatorChar + name + ".cs";
Debug.Log("Creating Classfile: " + copyPath);
if( File.Exists(copyPath) == false ){ // do not overwrite
using (StreamWriter outfile =
new StreamWriter(copyPath))
{
outfile.WriteLine("using UnityEngine;");
outfile.WriteLine("using System.Collections;");
outfile.WriteLine("");
outfile.WriteLine("public class "+name+" : MonoBehaviour {");
outfile.WriteLine(" ");
outfile.WriteLine("}");
}//File written
}
// Open the file in the default editor to start coding right away
UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(copyPath, 0);
// Keep a reference for later
EditorPrefs.SetString ("New Class Name", name);
EditorPrefs.SetInt("Selected GameObject Name", go.GetInstanceID());
// refresh so that the script gets compiled
AssetDatabase.Refresh();
}
}
[UnityEditor.Callbacks.DidReloadScripts]
private static void ScriptReloaded()
{
// If the key doesn’t exist, don’t bother, as we’re not generating stuff.
if (!EditorPrefs.HasKey ("New Class Name") || !EditorPrefs.HasKey ("Selected GameObject Name"))
{
return;
}
// If they key does exist and the object doesn’t, it’s just a left over key.
string name = EditorPrefs.GetString ("New Class Name");
int goName = EditorPrefs.GetInt("Selected GameObject Name");
GameObject go = EditorUtility.InstanceIDToObject(goName) as GameObject;
if (go == null)
{
Debug.Log("Object not found");
return;
}
Type type = Activator.CreateInstance("Assembly-CSharp", name).Unwrap().GetType();
go.AddComponent(type);
//Delete the key because we don’t need it anymore!
EditorPrefs.DeleteKey("New Class Name");
EditorPrefs.DeleteKey("Selected GameObject Name");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment