Skip to content

Instantly share code, notes, and snippets.

@mmoczkowski
Created June 29, 2015 12:26
Show Gist options
  • Save mmoczkowski/b34db3fdf8e6c8b2b116 to your computer and use it in GitHub Desktop.
Save mmoczkowski/b34db3fdf8e6c8b2b116 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEditorInternal;
[InitializeOnLoad]
public static class MecanimParamsGeneration {
[MenuItem ("Code Generation/Mecanim Params")]
private static void Generate() {
foreach(UnityEditor.Animations.AnimatorController myController in Resources.FindObjectsOfTypeAll<UnityEditor.Animations.AnimatorController>()) {
string className = ToPascalCase(myController.name);
string path = string.Concat( Application.dataPath, Path.DirectorySeparatorChar, "Scripts/Generated/", className, ".cs");
try
{
// opens the file if it allready exists, creates it otherwise
using ( FileStream stream = File.Open( path, FileMode.Create, FileAccess.Write ) )
{
using( StreamWriter writer = new StreamWriter(stream) )
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("// ----- AUTO GENERATED CODE ----- //");
builder.AppendLine("namespace Mecanim {");
builder.AppendLine("public static class " + className);
builder.AppendLine("{");
foreach(UnityEngine.AnimatorControllerParameter myParam in myController.parameters) {
string paramName = myParam.name.ToUpperInvariant();
int paramHash = myParam.nameHash;
builder.AppendLine( string.Format("\tpublic const int {0} = {1};", paramName, paramHash));
}
builder.AppendLine("}");
builder.AppendLine("} // end of namespace");
writer.Write( builder.ToString() );
}
}
}
catch(System.Exception e)
{
Debug.LogException( e );
// if we have an error, it is certainly that the file is screwed up. Delete to be save
if(File.Exists( path ) == true)
File.Delete( path );
}
AssetDatabase.Refresh();
}
}
public static string ToPascalCase(this string the_string)
{
// If there are 0 or 1 characters, just return the string.
if (the_string == null) return the_string;
if (the_string.Length < 2) return the_string.ToUpper();
the_string = the_string.Replace('_', ' ');
// Split the string into words.
string[] words = the_string.Split(
new char[] { },
StringSplitOptions.RemoveEmptyEntries);
// Combine the words.
string result = "";
foreach (string word in words)
{
result +=
word.Substring(0, 1).ToUpper() +
word.Substring(1);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment