Created
June 26, 2018 20:47
-
-
Save jfranmora/1fc88262088a29a493eea11ddc643c29 to your computer and use it in GitHub Desktop.
Function to autogenerate a script with the events of an animator as Unity Events ^^ (Works for events with 0 arguments)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
public class AnimatorEventsGenerator | |
{ | |
private const string ScriptTemplate = "// AUTOGENERATED CODE: {CLASSNAME}\n" + | |
"\nusing UnityEngine;" + | |
"\nusing UnityEngine.Events;\n" + | |
"\nnamespace AnimatorEvents { public class {CLASSNAME} : MonoBehaviour { {BODY} }}"; | |
private const string FunctionTemplate = "\npublic UnityEvent On{EVENTNAME}; " + | |
"\npublic void {EVENTNAME}() { On{EVENTNAME}.Invoke(); }"; | |
[MenuItem("CONTEXT/Animator/Generate Animator Events Code")] | |
public static void GenerateCodeFromAnimator(MenuCommand command) | |
{ | |
var animator = command.context as Animator; | |
GenerateCode_Internal(animator); | |
} | |
[MenuItem("CONTEXT/Animator/Generate Animator Events Code", true)] | |
private static bool GenerateCodeFromAnimator_Validate(MenuCommand command) | |
{ | |
var animator = command.context as Animator; | |
return animator.runtimeAnimatorController.animationClips.Length > 0; | |
} | |
private static void GenerateCode_Internal(Animator targetAnimator) | |
{ | |
// Path | |
var path = EditorUtility.SaveFilePanelInProject("Save file", | |
targetAnimator.gameObject.name.Replace(" ", "").Replace("-", "").Replace("_", "") + "_AnimatorEvents", "cs", | |
""); | |
if (path.Length == 0) return; | |
var scriptData = GenerateScriptData_Internal(path, targetAnimator); | |
WriteFile_Internal(path, scriptData); | |
} | |
private static string GenerateScriptData_Internal(string path, Animator animator) | |
{ | |
var scriptText = ScriptTemplate; | |
var bodyText = ""; | |
var eventName = new List<string>(); | |
foreach (var clip in animator.runtimeAnimatorController.animationClips) | |
{ | |
foreach (var ev in clip.events) | |
{ | |
eventName.Add(ev.functionName); | |
} | |
} | |
eventName = eventName.Distinct().ToList(); | |
foreach (var evName in eventName) | |
{ | |
bodyText += FunctionTemplate.Replace("{EVENTNAME}", evName); | |
} | |
scriptText = scriptText.Replace("{CLASSNAME}", Path.GetFileName(path).Replace(".cs", "")); | |
scriptText = scriptText.Replace("{BODY}", bodyText); | |
return scriptText; | |
} | |
private static void WriteFile_Internal(string path, string text) | |
{ | |
File.WriteAllText(path, text); | |
AssetDatabase.ImportAsset(path); | |
AssetDatabase.Refresh(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment