LoginSignup
0
1

【Unity×VRM1.0】読み込んだVRMオブジェクトをAnimatorで制御する

Posted at

概要

前回の続きです。

前回、フォルダから任意のVRMファイルを読み込めるようにしましたが、その読み込んだVRMのオブジェクトのAnimatorコンポーネントにはRuntimeAnimatorControllerがセットされていないため、アニメーションの制御ができません。
そこで、今回はアニメーションの制御を試しました。

結果は、以下の通り。Tポーズで読み込まれていたAvatarにIdleアニメーションをセットできました。

image.png

なお、Unityの使い方(AnimatorとかAnimatorControllerとか)についてはここでは触れませんので、必要ならキーワードから調べてみてください。

開発環境・使用したパッケージ

前回と同じです。

実装

Playモードに入りVRMファイルを読み込むと「VRM1」というゲームオブジェクトが生成されます。このゲームオブジェクトには、はじめからAnimatorコンポーネントがセットされているので、Controllerパラメータに事前に準備しておいたAnimatorControllerをセットすれば良いです。

image.png

上記を実現しているのが、SetAnimatorController()関数です。
なお、今回はセットするAnimatorControllerをSerializeFieldに予めセットしておく実装にしています。
セットし忘れると機能しないのでご注意ください。

UniVrm10.cs
using UnityEngine;
using System.Threading.Tasks;
using UniVRM10;
using SFB;

public class UniVrm10 : MonoBehaviour
{
    // デフォルトで読み込みたいモデルがある場合はpathをセットする。
    string path = "";

    [SerializeField] private RuntimeAnimatorController vrmAnimatorController;

    // Open file with filter
    // 拡張子がvrmまたはVRMのファイルのみ選択させる。
    ExtensionFilter[] extensions = new[] {
        new ExtensionFilter("VRM Files", "vrm", "VRM"),
    };

    // Start is called before the first frame update
    async void Start()
    {
        if (path != "" && path != null)
        {
            // VRMファイルのロード
            Vrm10Instance vrm10Instance = await Vrm10.LoadPathAsync(path);

            // セットされたVRMのAnimatorコンポーネントに事前に準備したRuntimeAnimationControllerをセット
            SetAnimatorController();
        }

    }

    // Update is called once per frame
    void Update() { }

    // ButtonコンポーネントとOn Click()にセットして利用することを想定
    public void LaodVRM()
    {
        string[] paths = StandaloneFileBrowser.OpenFilePanel("Load VRM File", "", extensions, true);
        // Vrm10Instance vrm10Instance = await Vrm10.LoadPathAsync(paths[0]);

        // すでに開かれているVRMファイルがある場合は削除する。
        GameObject currentVrm = GameObject.Find("VRM1");
        if (currentVrm != null)
        {
            Destroy(currentVrm);
        }
        OpenVRM(paths);
    }

    private async Task OpenVRM(string[] paths)
    {
        // VRMファイルのロード
        Vrm10Instance vrm10Instance = await Vrm10.LoadPathAsync(paths[0]);
        
        // セットされたVRMのAnimatorコンポーネントに事前に準備したRuntimeAnimationControllerをセット
        SetAnimatorController();
    }

    private void SetAnimatorController()
    {
        GameObject vrm1 = GameObject.Find("VRM1");
        Animator vrm1Animator = vrm1.GetComponent<Animator>();
        vrm1Animator.runtimeAnimatorController = vrmAnimatorController;
    }
}

利用方法

前回と同じです。
ただし、SerializeFieldにAnimatorControllerを予めセットするのを忘れないでください。

デモ画像で使用したアバター

New NecoMaid(製作:QuQu)

使用したIdleアニメーション

ただのIdleポーズではなく、ちゃんと呼吸のアニメーションが入っていて芸が細かいです。

参考資料

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1