Unity 对话系统中隐藏人物名字中的特定字符

在 Unity 对话系统中,有时需要隐藏人物名字中特定字符之间的所有内容。例如,人物名字 Lilybab 实际显示出来是 Lily。本教程将介绍如何实现这种功能。

代码实现

ChatPanel 类的 UpdateChat 方法中,可以使用字符串的 IndexOfLastIndexOf 方法来查找人物名字中的特定字符出现的位置,然后使用 Substring 方法来截取需要显示的部分字。

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

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

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

        // 截取人物名字中的 'b' 出现的位置之前的字
        string characterName = chatList[CurrentIndex].CharacterName;
        int startIndex = characterName.IndexOf('b');
        int endIndex = characterName.LastIndexOf('b');
        if (startIndex != -1 && endIndex != -1 && startIndex != endIndex)
        {
            characterName = characterName.Substring(0, startIndex) + characterName.Substring(endIndex + 1);
        }

        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();
    }
}

代码解释

  1. 获取人物名字:string characterName = chatList[CurrentIndex].CharacterName;
  2. 查找第一个 'b' 的位置:int startIndex = characterName.IndexOf('b');
  3. 查找最后一个 'b' 的位置:int endIndex = characterName.LastIndexOf('b');
  4. 判断是否找到 'b':if (startIndex != -1 && endIndex != -1 && startIndex != endIndex)
  5. 截取字符:characterName = characterName.Substring(0, startIndex) + characterName.Substring(endIndex + 1);

总结

通过以上代码,可以实现隐藏人物名字中特定字符之间的所有内容的功能。在实际应用中,可以根据需要修改代码中的特定字符,以及需要隐藏字符之间的内容。


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

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