Unity 实现简单的人物对话系统
生活随笔
收集整理的這篇文章主要介紹了
Unity 实现简单的人物对话系统
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文博客地址:Unity3D仿仙劍對話系統開發_紫丶光的博客-CSDN博客
博客中有兩處語法錯誤? 切割文本內容的時候和創建頭像的時候
創建一個cube作為點擊NPC的人物對象(掛載NPC腳本)?
創建一個空物體? GameManager(掛載Dialog腳本)?
場景中創建一個對話背景Image 對話文本1(人物名字) 對話文本2(對話內容)? Image 人物頭像? ?運行時點擊Cube即可看見效果
對話文本內容如下,text文本保存格式一定是UTF-8 ,不然不會顯示中文,創建好之后直接拖入Unity中即可使用
云天河%夢璃……是你嗎?%0
云天河%是你回來了嗎?%0
柳夢璃%云公子……是我……%1
柳夢璃%云公子……你還好嗎……%1
云天河%夢璃……我很好,你終于回來了……%0
柳夢璃%云公子,你的眼睛怎么了……%1
云天河%不礙事……倒是你,香味老遠就聞到了……%0
柳夢璃%(哭泣)云公子……%1
云天河%回來就好…%0
腳本代碼:
using System.Collections; using System.Collections.Generic; using UnityEngine;public class NPC : MonoBehaviour {public TextAsset _mTextAsset; //文本資源private void OnMouseDown() { Dialog.share.CreateDialogue(_mTextAsset); } void Start () {}void Update () {} }空物體上的腳本:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using DG.Tweening; public class Dialog : MonoBehaviour {public static Dialog share;public List<string[]> List_diaContents = new List<string[]>(); //用來存儲所有的對話內容public Image dialogueBg; //對話款背景 public Text _textName; //對話人物的名字 public Text _textContent; //對話人物說的話 public Image _imageHead; //頭像 public Sprite[] IconSprites;//所有頭像集合private bool isChat = false; //是否在對話 private int index; //對話內容的索引 private Tweener tweener; //對話框進入和離開屏幕的動畫private void Awake() { share = this; } void Start () { tweener = dialogueBg.rectTransform.DOLocalMoveY(-150, 0.5f).SetEase(Ease.InBack) .SetAutoKill(false); tweener.Pause(); //動畫一開始設置為暫停 IconSprites = Resources.LoadAll<Sprite>("Icon"); //獲取所有頭像集合 }/// <summary> /// 創建一個對話框 /// </summary> /// <param name="_mTextAsset">文本資源</param> public void CreateDialogue(TextAsset _mTextAsset) { if (isChat) { Debug.Log("111"); return; } List_diaContents.Clear();//每次都清空對話 List isChat = true; //初始化文本資源里的對話內容 string[] textAll = _mTextAsset.text.Split('\n');//先根據換行符切割出每一行文字 for (int i = 0; i < textAll.Length; i++) { string[] contents = textAll[i].Split('%'); //根據%切割出三個 0 名字 1說的話 2頭像 List_diaContents.Add(contents); //把名字 對話 頭像 存進List } Debug.Log("222"); tweener.PlayForward(); //播放對話框進入屏幕的動畫 }void Update () { if (isChat) //當打開對話框時 { if (Input.GetMouseButtonDown(0)||Input.GetKeyDown(KeyCode.Space)) { Debug.Log("333");// if (index>=List_diaContents.Count) //當對話到了最后一步 { tweener.PlayBackwards(); //倒放對話框動畫 index = 0; isChat = false;//關閉 } else { _textName.text = List_diaContents[index][0]; //顯示對話人物的名稱 _textContent.text = List_diaContents[index][1];//顯示對話的內容 int i = int.Parse(List_diaContents[index][2]); _imageHead.sprite = IconSprites[i];//顯示頭像 index++; //當前對話內容的索引 } } } } }總結
以上是生活随笔為你收集整理的Unity 实现简单的人物对话系统的全部內容,希望文章能夠幫你解決所遇到的問題。