メインコンテンツへスキップ

Unity6で、コマンドファイルを読み込んで、VRM1.0の表情を設定する

    ファイルを読み込んで、その指示に従って、表情を変更する。

    command.txtの例
    Sad, 2
    Happy, 2
    Fun, 2
    Surprised, 2
    Angry, 2

    using UnityEngine;
    using System.IO;
    using UniVRM10;
    using System.Collections;
    using UnityEngine.TextCore.Text;
    
    public class CommandController : MonoBehaviour
    {
        private Vrm10Instance _instance;
        private Vrm10RuntimeExpression expression;
        private string commandFilePath = "/tmp/unity/command.txt";
    
        void Start()
        {
            _instance = GetComponent<Vrm10Instance>();
            if (_instance == null) { Debug.LogError("Vrm10Instance が見つかりません"); enabled = false; return; }
    
            expression = _instance.Runtime.Expression;
            if (expression == null) { Debug.LogError("Expressionがnullです"); enabled = false; return; }
    
            StartCoroutine(ReadCommandLoop());
        }
    
        IEnumerator ReadCommandLoop()
        {
            while (true)
            {
                if (File.Exists(commandFilePath))
                {
                    string content = File.ReadAllText(commandFilePath);
                    File.Delete(commandFilePath);
                    string[] lines = content.Split('\n');
    
                    foreach (string line in lines)
                    {
                        if (string.IsNullOrWhiteSpace(line)) continue;
                        string[] parts = line.Trim().Split(',');
                        if (parts.Length >= 2 && float.TryParse(parts[1].Trim(), out float duration))
                        {
                            // 直接順番に実行(前の表情が終わるまで待機)
                            yield return StartCoroutine(PlayExpressionCoroutine(
                                parts[0].Trim().ToLower(), duration));
                        }
                    }
                }
                yield return new WaitForSeconds(0.1f);
            }
        }
    
        IEnumerator PlayExpressionCoroutine(string emotionName, float duration)
        {
            ExpressionKey? keyNullable = GetExpressionKey(emotionName);
            if (!keyNullable.HasValue) yield break;
            ExpressionKey key = keyNullable.Value;
    
            expression.SetWeight(key, 1.0f);
            yield return new WaitForSeconds(duration);
            expression.SetWeight(key, 0.0f);
        }
    
        ExpressionKey GetExpressionKey(string name) => name switch
        {
            "fun" or "happy" => ExpressionKey.Happy,
            "sad" => ExpressionKey.Sad,
            "angry" => ExpressionKey.Angry,
            "surprised" => ExpressionKey.Surprised,
            "relaxed" => ExpressionKey.Relaxed,
            _ => ExpressionKey.Neutral
        };
    }
    


    あなたへのおすすめ