UnityNovelProj Unity で VisualNovel を作成する

Narrator "hello, new character <mainChara>"
<mainChara> "My name is <mainChara>.{c} What time is it?"
Narrator "<time> is!"

<\w+> というフォーマットを Tag として扱い、そのタグがあったら置換する、という仕組みを追加しました。 これによって

  • 主人公の名前を一括置換する
  • 特定の日付を入れる
  • 変数を入れる

などが行えるようになります。 タグシステムは便利なので自分でも実装したいです。

    public class TagManager
    {
        private readonly Dictionary<string, Func<string>> tags = new();
        private readonly Regex tagRegex = new("<\\w+>");
 
        public TagManager()
        {
            InitializeTags();
        }
 
        private void InitializeTags()
        {
            /**
             * TODO:  スクリプトや設定ファイルから設定できるようにする
             */
            tags["<mainChara>"] = () => "Avira";
            tags["<time>"] = () => DateTime.Now.ToString("hh:mm tt");
            tags["<playerLevel>"] = () => "15";
            tags["<tempVal1>"] = () => "42";
        }
 
        /// <summary>
        /// `text` というもともとの文章が与えられる
        /// `text` に登録済みのタグが含まれていればそれを置換する
        /// </summary>
        public string Inject(string text)
        {
            if (!tagRegex.IsMatch(text))
            {
                return text;
            }
 
            foreach (Match match in tagRegex.Matches(text))
            {
                if (tags.TryGetValue(match.Value, out var tagFunc))
                {
                    text = text.Replace(match.Value, tagFunc());
                }
            }
 
            return text;
        }
    }
 

注意点として rawText を TagManager で置換するのではなく

  • 名前を表示するとき
  • dialogueSegment を表示するとき

という、直前に置換しています。

これは <mainChara> など、話者名で character の設定 config を用意しているのですが、先に置換されると <mainChara> の config が適用されないためです。

そのため、話者名を表示するときに直前で置換しています。

url: https://www.youtube.com/watch?v=Vxp834m8yJc&list=PLGSox0FgA5B58Ki4t4VqAPDycEpmkBd0i&index=57
title: "Make a Visual Novel in Unity 2023 - Episode 17 Tag Manager"
description: "Let's inject dynamic data into our dialogue system by using tags in the text and a new tag system.Other Links: - Discord Server   - https://discord.gg/xVTZSg..."
host: www.youtube.com
favicon: https://www.youtube.com/s/desktop/c81c827c/img/logos/favicon_32x32.png
image: https://i.ytimg.com/vi/Vxp834m8yJc/maxresdefault.jpg