Unity 对话系统:隐藏人物名字中两个 'b' 之间的文字

本教程介绍如何在 Unity 对话系统中实现隐藏人物名字里两个 'b' 之间的文字,例如人物名称为 Lilybab,实际显示出来是 Lily。

实现方法:

TypeText 方法中,添加一个 bool 类型的变量 isHiding,用于判断是否需要隐藏文字。初始值设为 false

private IEnumerator TypeText(string text)
{
    int length = text.Length;
    bool isHiding = false;

    for (int i = 0; i < length; i++)
    {
        if (text[i] == 'b' && i < length - 1 && text[i + 1] == 'b')
        {
            isHiding = !isHiding;
            i++; // 跳过下一个 'b'
        }
        else if (!isHiding)
        {
            dialogdata.text += text[i];
        }

        yield return new WaitForSeconds(0.07f);
    }

    isShowingComplete = true;
}

解释:

  1. 当遇到连续的两个 'b' 时,isHiding 的值会取反,从而实现隐藏和显示之间的文字。
  2. i++ 用于跳过下一个 'b',避免重复判断。
  3. else if (!isHiding) 条件保证只有当 isHidingfalse 时才会显示文字。

注意:

如果要隐藏的文字不仅限于两个 'b' 之间的文字,可以修改判断条件来适应其他情况。

示例代码:

using UnityEngine;
using UnityEngine.UI;
using QFramework;
using System.Collections;
using System.Collections.Generic;

namespace QFramework.Escape
{
    public class ChatPanelData : UIPanelData
    {
        // 对话列表
        public List<ChatItem> chatList;
        // 对话后触发的事件Code
        public string EventCode;
    }

    public partial class ChatPanel : UIPanel
    {
        // 对话完成的回调
        public delegate void ChatCallback();

        // 对话的当前索引
        private int CurrentIndex = 0;

        // 对话列表
        private List<ChatItem> chatList;

        // 协程
        private Coroutine mCoroutine;

        // 是否完全显示对话
        private bool isShowingComplete = false;

        protected override void OnInit(IUIData uiData = null)
        {
            mData = uiData as ChatPanelData ?? new ChatPanelData();
            chatList = (mData as ChatPanelData).chatList;
            CurrentIndex = 0;
            UpdateChat();
            nextButton.onClick.AddListener(() =>
            {
                Debug.Log('click');
                if (isShowingComplete)
                {
                    UpdateChat();
                }
                else
                {
                    CompleteCurrentText();
                }
            });
        }

        protected void UpdateChat()
        {
            if (CurrentIndex < chatList.Count)
            {
                dialogdata.text = '';
                isShowingComplete = false;

                if (mCoroutine != null)
                {
                    StopCoroutine(mCoroutine);
                    mCoroutine = null;
                }

                mCoroutine = StartCoroutine(TypeText(chatList[CurrentIndex].Dialog));

                if (chatList[CurrentIndex].Position == ChatPosition.Left)
                {
                    ImageLeft.sprite = ChatSystem.Instance.imageDic[chatList[CurrentIndex].CharacterName];
                    LeftName.text = ChatSystem.Instance.GetCharacterName(chatList[CurrentIndex].CharacterName);
                    ImageLeft.gameObject.SetActive(true);
                    ImageRight.gameObject.SetActive(false);
                    LeftName.gameObject.SetActive(true);
                    RightName.gameObject.SetActive(false);
                }
                else
                {
                    ImageRight.sprite = ChatSystem.Instance.imageDic[chatList[CurrentIndex].CharacterName];
                    RightName.text = ChatSystem.Instance.GetCharacterName(chatList[CurrentIndex].CharacterName);
                    ImageLeft.gameObject.SetActive(false);
                    ImageRight.gameObject.SetActive(true);
                    LeftName.gameObject.SetActive(false);
                    RightName.gameObject.SetActive(true);
                }
                CurrentIndex++;
            }
            else
            {
                CloseSelf();
            }
        }

        private IEnumerator TypeText(string text)
        {
            int length = text.Length;
            bool isHiding = false;

            for (int i = 0; i < length; i++)
            {
                if (text[i] == 'b' && i < length - 1 && text[i + 1] == 'b')
                {
                    isHiding = !isHiding;
                    i++; // 跳过下一个 'b'
                }
                else if (!isHiding)
                {
                    dialogdata.text += text[i];
                }

                yield return new WaitForSeconds(0.07f);
            }

            isShowingComplete = true;
        }

        private void CompleteCurrentText()
        {
            StopCoroutine(mCoroutine);
            dialogdata.text = chatList[CurrentIndex - 1].Dialog;
            isShowingComplete = true;
        }

        protected override void OnOpen(IUIData uiData = null)
        {
            Player.Instance.Blocking = true;
        }

        protected override void OnShow()
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnClose()
        {
            Player.Instance.Blocking = false;
            if (mData.EventCode != '' && mData.EventCode != null)
            {
                GameEventHandle.Instance.MakeEventInfluence(mData.EventCode);
            }

            mCoroutine = null;
        }
    }
}
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
using System;


// 定义方向枚举
public enum ChatPosition
{
    Left,
    Right
}

namespace QFramework.Escape
{
    // 定义角色枚举
    public enum Character
    {
        None,
        Destiney,
        Lily,
        Dylan,
        H1,
        H2,
        Lilybsickb,
        Lilybcourageb,
        Lilybshockb,
        Lilyblaughb,
        Lilybforcedsmileb,
        Lilyblaughcloseb,
        Lilybforcedsmilecloseb,
        Lilybsmilecloseb,
        Lilybseriousb
        

    }



    [Serializable]
    public class ChatSystem : SerializedMonoBehaviour
    {
        private static ChatSystem instance;

        private static Dictionary<Character, string> CharacterNameDic = new Dictionary<Character, string>();
        private static Dictionary<string, Character> NameToCharacterDic = new Dictionary<string, Character>();

        /// <summary>
        /// 对话文本文件,csv格式
        /// </summary>
        public TextAsset dialogDataFile;

        [SerializeField]
        [DictionaryDrawerSettings(KeyLabel = '角色标识', ValueLabel = '角色信息')]
        public Dictionary<Character, Sprite> imageDic = new Dictionary<Character, Sprite>();
        /// <summary>
        /// 角色名字对应图片字典,把角色名字“string”指向对应的图片“sprite”
        /// </summary>
        /// 

        /// <summary>
        /// 保存当前的对话索引值
        /// </summary>
        public int dialogIndex;
        /// <summary>
        /// 对话文本,按行分割
        /// </summary>
        public string[] dialogRows;

        public static ChatSystem Instance { get => instance; set => instance = value; }

        private void Awake()
        {
            Instance = this;
            InitDic();
        }

        private void InitDic()
        {
            CharacterNameDic.TryAdd(Character.Destiney, 'Destiney');
            CharacterNameDic.TryAdd(Character.Lily, 'Lily');
            CharacterNameDic.TryAdd(Character.Dylan, 'Dylan');
            CharacterNameDic.TryAdd(Character.None, '');
            CharacterNameDic.TryAdd(Character.H1, 'H1');
            CharacterNameDic.TryAdd(Character.H2, 'H2');
            CharacterNameDic.TryAdd(Character.Lilybsickb, 'Lilysick');
            CharacterNameDic.TryAdd(Character.Lilybcourageb, 'Lilycourage');
            CharacterNameDic.TryAdd(Character.Lilybshockb, 'Lilyshock');
            CharacterNameDic.TryAdd(Character.Lilyblaughb, 'Lilylaugh');
            CharacterNameDic.TryAdd(Character.Lilybforcedsmileb, 'Lilyforcedsmile');
            CharacterNameDic.TryAdd(Character.Lilyblaughcloseb, 'Lilylaughclose');
            CharacterNameDic.TryAdd(Character.Lilybforcedsmilecloseb, 'Lilyforcedsmileclose');
            CharacterNameDic.TryAdd(Character.Lilybsmilecloseb, 'Lilysmileclose');
            CharacterNameDic.TryAdd(Character.Lilybseriousb, 'Lilyserious');
            foreach (var item in CharacterNameDic)
            {
                NameToCharacterDic.TryAdd(item.Value, item.Key);
            }
        }

        public string GetCharacterName(Character character)
        {
            return CharacterNameDic[character];
        }

        // Start is called before the first frame update
        void Start()
        {

        }


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

        }


        //public void UpdateText(string _name, string _text)//此处为文本的更新(每点击一次就会调用该函数更新文本)
        //{
        //    IntoDialog();
        //    nameText.text = _name;
        //    dialogText.text = _text;

        //}


        //public void UpDateImage(string _name, string _position)//此处为角色立绘的更新(会根据当前的对话匹配对应的角色)
        //{
        //    if (_position == '左')
        //    {
        //        spriteLeft.gameObject.SetActive(true);
        //        spriteRight.gameObject.SetActive(false);
        //        spriteLeft.sprite = imageDic[_name];
        //        //SourseImage.sprite = imageDic[_name];//在imaginedictionary中寻找到该角色的名字,从而找到对应立绘放在左侧
        //    }  
        //    else if (_position == '右')
        //    {
        //        spriteLeft.gameObject.SetActive(false);
        //        spriteRight.gameObject.SetActive(true);
        //        spriteRight.sprite = imageDic[_name];//否则则放在右侧
        //    }
        //}
        public void ReadText(TextAsset _textAsset)
        {
            dialogRows = _textAsset.text.Split('
');
            //foreach (var dialog in rows)
            //{
            //    string[] cell = row.Split(',');
            //}
            Debug.Log('读取成功');
        }
        public UIPanel ShowDialogRow(TextAsset _textAsset,string eventCode)
        {
            dialogRows = _textAsset.text.Split('
');
            List<ChatItem> list = new List<ChatItem>();
            for (int i = 0; i < dialogRows.Length; i++)
            {
                string[] cells = dialogRows[i].Split(',');
                if (cells[0] == '#' && int.Parse(cells[1]) == dialogIndex)
                {
                    ChatPosition pos;
                    if (cells[3] == '左')
                    {
                        pos = ChatPosition.Left;
                    }
                    else
                    {
                        pos = ChatPosition.Right;
                    }
                    list.Add(new ChatItem()
                    {
                        CharacterName = ChatSystem.NameToCharacterDic[cells[2]],
                        Dialog = cells[4],
                        Position = pos,
                    });
                    dialogIndex = int.Parse(cells[5]);
                    //nextButton.gameObject.SetActive(true);
                    //break;
                }
                else if (cells[0] == 'END' && int.Parse(cells[1]) == dialogIndex)
                {
                    dialogRows = new string[0];
                    dialogIndex = 0;
                }
            }
            return UIKit.OpenPanel<ChatPanel>(new ChatPanelData {
                chatList = list,
                EventCode = eventCode
            });
        }

    }

}
Unity 对话系统:隐藏人物名字中两个 'b' 之间的文字

原文地址: https://www.cveoy.top/t/topic/ph0c 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录