Skip to content

Instantly share code, notes, and snippets.

@GieziJo
Last active February 19, 2020 06:59
Show Gist options
  • Save GieziJo/9431390998734cde21d6a6e0f77ce72d to your computer and use it in GitHub Desktop.
Save GieziJo/9431390998734cde21d6a6e0f77ce72d to your computer and use it in GitHub Desktop.
Unity - add Animator, Animator Controller and Animation to GameObject in hierarchy
// ===============================
// AUTHOR : J. Giezendanner
// CREATE DATE : 18.02.2020
// MODIFIED DATE :
// PURPOSE : Adds a context menu to create an Animator Component, Animator Controller
// and Animation to a GameObject in the hierarchy
// SPECIAL NOTES :
// ===============================
// Change History:
//==================================
using System.IO;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Editor
{
public static class AnimatorHelper
{
[MenuItem("GameObject/Giezi's tools/Add Animator, Animator Controller and Animation", false, 0)]
static void AddRequiredComponents()
{
if (Selection.activeGameObject != null)
{
GameObject go = Selection.activeGameObject;
Animator animator;
string assetPath = Application.dataPath + Path.DirectorySeparatorChar + "Animations" + Path.DirectorySeparatorChar;
string path = EditorUtility.SaveFilePanel("Save controller and animation", assetPath, "New Animation","");
if (path.Length == 0)
return;
if (go.GetComponent<Animator>() != null)
{
Debug.Log("Object already contains animator");
if (EditorUtility.DisplayDialog("Use existing animator?",
"Are you sure you want to use the existing animator?", "Yes", "No"))
animator = go.GetComponent<Animator>();
else
{
Debug.Log("Aborted operation");
return;
}
}else
animator = go.AddComponent<Animator>();
path = path.Replace(Application.dataPath + Path.AltDirectorySeparatorChar, "");
path = "Assets" + Path.AltDirectorySeparatorChar + path;
string name = Path.GetFileNameWithoutExtension(path);
string dir = Path.GetDirectoryName(path);
AnimationClip clip = new AnimationClip();
AnimationClipSettings settings = AnimationUtility.GetAnimationClipSettings(clip);
settings.loopTime = true;
AnimationUtility.SetAnimationClipSettings(clip,settings);
AssetDatabase.CreateAsset(clip, dir + Path.DirectorySeparatorChar + name + ".anim");
AnimatorController animatorController = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPathWithClip(dir + Path.DirectorySeparatorChar + name + ".controller", clip);
animator.runtimeAnimatorController = animatorController;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment