Skip to content

Instantly share code, notes, and snippets.

@rje
Created July 13, 2016 22:00
Show Gist options
  • Select an option

  • Save rje/13ebe18fa0e6ef322c5dc0b44cc472f2 to your computer and use it in GitHub Desktop.

Select an option

Save rje/13ebe18fa0e6ef322c5dc0b44cc472f2 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
public class CreateLayerConstants
{
const string CLASS_NAME = "LayerConstants";
const string FILE_PATH = "Assets/Scripts/Generated/";
[MenuItem("Assets/Update Layer Constants")]
public static void UpdateLayerConstants()
{
string[] values = new string[32];
for (var i = 0; i < 32; i++)
{
var newValue = LayerMask.LayerToName(i);
if (newValue != values[i])
{
values[i] = newValue;
}
}
WriteLayerClass(values);
}
public static string GetFilename()
{
return string.Format("{0}.cs", CLASS_NAME);
}
public static string GetPath()
{
return Path.Combine(FILE_PATH, GetFilename());
}
public static void WriteLayerClass(string[] values)
{
Debug.Log("Writing layer values!");
var path = GetPath();
var dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var toWrite = GenerateClassText(values);
File.WriteAllText(path, toWrite);
AssetDatabase.Refresh();
}
public static string GenerateClassText(string[] values)
{
var sb = new StringBuilder();
sb.AppendFormat("public class {0} {{\n", CLASS_NAME);
for (var i = 0; i < values.Length; i++)
{
if (string.IsNullOrEmpty(values[i]))
{
continue;
}
var layer = values[i];
var constName = layer.ToUpper().Replace(' ', '_');
sb.AppendFormat("\tpublic const string {0} = \"{1}\";\n", constName, layer);
sb.AppendFormat("\tpublic const int {0}_NUMBER = {1};\n", constName, i);
sb.AppendLine();
}
sb.Append("}");
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment