代码实现
CSV数据
TimeLine
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using UnityEngine.UI;
public class NpcContent
{
//CSV解析需要的属性
public string chatId;
public string npc;
public string content;
public string type;
public string[] options;
public string[] replyid;
public string openid;
public NpcContent(string[] str)
{
this.chatId = str[0];
this.npc = str[1];
this.content = str[2];
this.type = str[3];
this.options = str[4].Split('|');
this.replyid = str[5].Split('|');
this.openid = str[6];
}
}
public class Npc : MonoBehaviour, ITimeControl
{
public GameObject chat;
public GameObject prefab;
public PlayableDirector director;
public string[] strs;
public string chatId = "0";
Text[] chatText;
public TextAsset npcCsv;
Dictionary<string, NpcContent> npcDic = new Dictionary<string, NpcContent>();
public GameObject btnPrefab;
private void Start()
{
director = GetComponent<PlayableDirector>();
string[] line = npcCsv.text.Split('\n');
for (int i = 1; i < line.Length - 1; i++)
{
NpcContent npcContent = new NpcContent(line[i].Split(','));
npcDic.Add(npcContent.chatId, npcContent);
}
print(npcDic);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
director.Play();
}
}
//开始
public void OnControlTimeStart()
{
if (chat == null)
{
chat = Instantiate(prefab, GameObject.Find("Canvas").transform);
chatText = chat.GetComponentsInChildren<Text>();
chatText[0].text = "小花";
}
}
//结束
public void OnControlTimeStop()
{
if (chat != null)
{
director.Pause();
switch (npcDic[chatId].type)
{
case "0":
Destroy(chat);
chat = null;
break;
case "1":
Transform btnBox = chat.transform.Find("BtnS");
for (int i = btnBox.childCount - 1; i >= 0; i--)
{
Destroy(btnBox.GetChild(i).gameObject);
}
for (int i = 0; i < npcDic[chatId].options.Length; i++)
{
GameObject chatBtn = Instantiate(btnPrefab, chat.transform.Find("BtnS").transform);
chatBtn.GetComponentInChildren<Text>().text = npcDic[chatId].options[i];
string replyid = npcDic[chatId].replyid[i];
chatBtn.GetComponent<Button>().onClick.AddListener(() =>
{
if (replyid == "-1")
{
Destroy(chat);
chat = null;
director.Play();
chatId = "0";
}
else
{
chatId = replyid;
director.time = 1;
director.Play();
}
});
}
break;
case "2":
Destroy(chat);
chat = null;
director.Play();
chatId = "0";
break;
}
}
}
//TimeLine时间
public void SetTime(double time)
{
print(time);
if (chat != null)
{
if (npcDic[chatId].content.Length >= (int)(time * 2.1f))
{
chatText[1].text = npcDic[chatId].content.Substring(0, (int)(time * 2.1f));
}
else if (time < 6)
{
director.time = 6;
}
}
}
}