Skip to content

Instantly share code, notes, and snippets.

@shivaduke28
Last active March 16, 2022 13:44
Show Gist options
  • Save shivaduke28/6193edbe7f040785651c09d6cd533955 to your computer and use it in GitHub Desktop.
Save shivaduke28/6193edbe7f040785651c09d6cd533955 to your computer and use it in GitHub Desktop.
create HLSL file in Unity
using UnityEditor;
using System.IO;
using System.Linq;
namespace TKMNY.Editor
{
public static class ShaderUtility
{
private const string DefaultHLSLTemplate = @"
#ifndef <TemplateName>_INCLUDED
#define <TemplateName>_INCLUDED
#endif
";
[MenuItem("Assets/Create/TKMNY/HLSL", false, 1)]
static void CreateHLSLFile()
{
string folderPath = "Assets/";
if (Selection.activeObject != null)
{
folderPath = AssetDatabase.GetAssetPath(Selection.activeObject);
if (Selection.activeObject.GetType() != typeof(DefaultAsset))
{
folderPath = Path.GetDirectoryName(folderPath);
}
}
else if (Selection.assetGUIDs.Length > 0)
{
folderPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
}
folderPath = folderPath.Replace('\\', '/');
var chosenFilePath = EditorUtility.SaveFilePanelInProject("Save HLSL File", "", "hlsl", "Save HLSL file", folderPath);
if (!string.IsNullOrEmpty(chosenFilePath))
{
var chosenFileName = Path.GetFileNameWithoutExtension(chosenFilePath).Replace(" ", "");
var template = DefaultHLSLTemplate;
template = template.Replace("<TemplateName>", ConvertToScreamingCase(chosenFileName));
File.WriteAllText(chosenFilePath, template, System.Text.Encoding.UTF8);
AssetDatabase.ImportAsset(chosenFilePath, ImportAssetOptions.Default);
}
}
static string ConvertToScreamingCase(string str)
{
return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToUpper();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment