Skip to content

Instantly share code, notes, and snippets.

@RoxDevvv
Created July 24, 2024 10:23
Show Gist options
  • Save RoxDevvv/e94aab3855f10ba26b9fe402aa124cc6 to your computer and use it in GitHub Desktop.
Save RoxDevvv/e94aab3855f10ba26b9fe402aa124cc6 to your computer and use it in GitHub Desktop.
Unity Script templates Creation
// Place this script in 'Editor' Folder
// Create a folder named 'Templates' at the same directory level as the 'Editor' folder, but outside of it.
// Create 'ScriptName.cs.txt' in 'Templates' Folder
// Done
using System.IO;
using UnityEditor;
using UnityEngine;
public class CreateScriptFromTemplate
{
readonly static string templateName = "ScriptName.cs.txt";
[MenuItem(itemName: "Assets/Create/MyTemplates/Create name Script", isValidateFunction: false)]
public static void CreateScriptFromTemplateMethod()
{
string[] guids = AssetDatabase.FindAssets("CreateScriptFromTemplate t:Script");
if (guids.Length == 0)
{
Debug.LogError("Class script not found: CreateScriptFromTemplate.cs");
return;
}
// Get the path to the first match
string scriptPath = AssetDatabase.GUIDToAssetPath(guids[0]);
string directoryPath = Path.GetDirectoryName(scriptPath);
if (directoryPath != null && directoryPath.Contains("Editor"))
{
string templatePath = Path.Combine(directoryPath, $"../Templates/{templateName}");
string destName = Path.GetFileNameWithoutExtension(scriptPath);
CreateScriptAsset(templatePath, destName);
}
else
{
Debug.LogWarning("The specified part of the path was not found in the script path.");
}
}
static void CreateScriptAsset(string templatePath, string destName)
{
#if UNITY_2019_1_OR_NEWER
ProjectWindowUtil.CreateScriptAssetFromTemplateFile(templatePath, destName);
#else
typeof(ProjectWindowUtil)
.GetMethod("CreateScriptAsset", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)
.Invoke(null, new object[] { templatePath, destName });
#endif
}
}
@RoxDevvv
Copy link
Author

An alternative method to achieve this without using a script.

Create a folder named 'ScriptTemplates' and place it directly inside the 'Assets' directory.

Template

In the 'ScriptTemplates' folder, you may create numerous script templates, provided they adhere to a strict naming convention. Please make sure that any script templates you create in your new ScriptTemplates folder strictly follow the prescribed naming convention.

script-templates

Example :
82-MyMenuName__Create My Script-MyScriptName.cs.txt

Content Example :

    public class #SCRIPTNAME# : MonoBehaviour
    {
        private void Start()
        {

        }
    }

Note: Changes will only take effect after you restart Unity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment