- Home /
Loading Animations via C# Script directly from .fbx?
Hey Guys, as the title of this question says, i want to load the animations from my .fbx model via c# (without the UnityEditor class!) and add them to the animation component (also added per script).
public class AnimatorController : MonoBehaviour {
public string modelName;
public string aniName;
public AnimationClip clip;
void Start ()
{
gameObject.AddComponent<Animation> ();
anim = gameObject.GetComponent <Animation> ();
clip = Resources.Load (modelName + ".fbx/idle", typeof(AnimationClip)) as AnimationClip;
clip.legacy = true;
anim.AddClip (clip, "idle");
anim.wrapMode = WrapMode.Loop;
anim.playAutomatically = true;
anim.Play ("idle");
}
}
After that clip still is null.
This is what the .fbx looks like in the project window:
I need that script to load and animate models without creating a prefab or using the inspector.
Thanks in advance.
Answer by soltex1 · May 01, 2016 at 07:21 AM
What I have tried:
I was trying to solve the problem but with a .blend file instead.
First of all, this:
Object animation_clips = Resources.LoadAssetAtPath("PATH-TO-YOUR-MODEL", typeof(AnimationClip));
returned only one animation clip, so, I thought that:
Object[] animation_clips = Resources.LoadAssetAtPath("PATH-TO-YOUR-MODEL", typeof(AnimationClip[]));
would return all, however, I was wrong, It returned an empty array.
Solution that I found out [using ModelImporter format]:
After some research, I found out this solution:
ModelImporter model_imp = AssetImporter.GetAtPath("PATH-TO-YOUR-MODEL") as ModelImporter;
For instance, to print all the animations, you can simple do:
foreach (var anim_clip model_imp.clipAnimations) { Debug.Log(anim.clip); }
Source: http://answers.unity3d.com/questions/674318/accessing-clipanimations-from-fbx-files.html
Afterwards problem and solution [using AnimationClip format]:
In my case, the animation clips in ModelImpoterAnimationClip format wasn't enough, because I couldn't use them as AnimationClip. So, I found out another solution to make the exact same thing, but loading the animation clips as AnimationClip format, using:
Resources.LoadAssetAtPath("PATH-TO-YOUR-MODEL", typeof(Motion[]))
var clips = Resources.FindObjectsOfTypeAll<AnimationClip>();
Now, you can do whatever you want, for instance print:
foreach (var c in clips) { Debug.Log(c.name); }
Hi, i'm having the same problem, but this script doesn't work... could you help me please?
Answer by wdr434-domowe · May 19, 2021 at 06:10 PM
I had issue because path to model was wrong. Try this solution:
string path = Application.dataPath + "/Resources/<model_name>.fbx";
var assetPath = path.Replace(Application.dataPath, "Assets");
ModelImporter MI = (ModelImporter)AssetImporter.GetAtPath(assetPath);
ModelImporterClipAnimation[] clips = MI.defaultClipAnimations;
foreach(var clip in clips) { Debug.Log(clip.name); }