How can I load motions and play them at runtime in Unity?
I have successfully loaded the Live2d model at runtime, added `Cusbism Fade Controller` and `Cubism Motion Controller` with using `AddComponent` method.
Then I load motion data from directory `C:/Live2DModels/hiyori_pro_zh/hiyori_pro_zh/runtime/motion`.
```C#
private void LoadMotionFromPath(string path)
{
var json = File.ReadAllText(path);
var motion3Json = CubismMotion3Json.LoadFrom(json);
var animationClip = motion3Json.ToAnimationClip();
_animationClips.Add(animationClip);
}
```
But when I use `_motionController.PlayAnimation(animationClip, isLoop: true);` to play, I got 1 error and 1 log.
```
CubismMotionController : CubismFadeMotionList doesn't set in CubismFadeController.
UnityEngine.Debug:LogError (object)
Live2D.Cubism.Framework.Motion.CubismMotionController:OnEnable () (at Assets/Live2D/Cubism/Framework/Motion/CubismMotionController.cs:261)
UnityEngine.GameObject:AddComponent ()
Unity.VisualScripting.ComponentHolderProtocol:AddComponent (UnityEngine.Object) (at Library/PackageCache/com.unity.visualscripting@1.9.4/Runtime/VisualScripting.Core/Utilities/ComponentHolderProtocol.cs:45)
Controller.MotionController:Start () (at Assets/Scripts/Controller/MotionController.cs:48)
```
```
can't start motion.
UnityEngine.Debug:Log (object)
Live2D.Cubism.Framework.Motion.CubismMotionController:PlayAnimation (UnityEngine.AnimationClip,int,int,bool,single) (at Assets/Live2D/Cubism/Framework/Motion/CubismMotionController.cs:109)
Controller.MotionController:PlayMotion (int) (at Assets/Scripts/Controller/MotionController.cs:98)
Controller.MotionController:Start () (at Assets/Scripts/Controller/MotionController.cs:60)
```
Then I checked the manual, it said that `Cusbism Fade Controller` should be set with `xxxx.fadeMotionList` for the field `Cubsim Fade Motion List`.
However, those `xxxx.fadeMotionList` are generated when I import a Live2d model through the Unity Editor. If I load the Live2d model at runtime (gamemode), all controllers (related components) are added at runtime, then how can I play the animation clip in such situation?
0 ·
Answers
https://docs.live2d.com/cubism-sdk-manual/faq/
Here is the code snippet that load motion json files from specific directory, add all animation clips in the Animation component and play the first of them.
```C#
private void LoadMotionsFromPath(string motionsDir)
{
var animation = _model.AddComponent();
FolderTraverser.TraverseFolders(motionsDir, (file) =>
{
var json = File.ReadAllText(file);
var motion3Json = CubismMotion3Json.LoadFrom(json);
var animationClip = motion3Json.ToAnimationClip();
animationClip.legacy = true;
var animName = Path.GetFileNameWithoutExtension(file);
animationClip.name = animName;
_animationClips.Add(animationClip);
});
foreach (var animationClip in _animationClips)
{
animation.AddClip(animationClip, animationClip.name);
}
animation.Play(_animationClips[0].name);
}
```