我希望在开头的时候,能有一个讲故事的Scene来讲前置剧情,就写了个类。用来控制文本逐字显示的:
[RequireComponent(typeof(Text))] public class TextController : MonoBehaviour{ public bool m_isUseBtn = true; //是否使用按钮 public Button m_btn; //按钮 public float m_time = 0.05f; //字符显示间隔时间 public string m_str = "this is test string."; //将要显示的文本 public bool m_isUseAutoPlay = true; //是否使用自动播放 public float[] m_times; //自动播放间隔时间 private string s = ""; //单个字符 private Text m_text; //文本显示的区域 private int textIndex; //文本标号 private float time = 0; void Start() { textIndex = 0; m_text = this.GetComponent<Text>(); if (m_isUseBtn && m_btn) { m_btn.GetComponent<Button>().onClick.AddListener(() => { OnTheClick(); }); } PlayText(); } private void Update() { time += Time.deltaTime; if (ES3.KeyExists(textIndex.ToString(), "0_0")) { if (m_times != null && m_times.Length >= textIndex) { if (time >= m_times[textIndex - 1]) { PlayText(); } } else { if (time >= 5) { PlayText(); } } } } private void PlayText() { m_text.text = ""; m_str = ES3.Load<string>(textIndex.ToString(), "0_0"); textIndex++; time = 0; StartCoroutine(ShowText(m_str.Length)); } /// <summary> /// 协程显示 /// </summary> /// <param name="strLength">欲显示的长度</param> /// <returns></returns> IEnumerator ShowText(int strLength) { int i = 0; s = ""; while (i < strLength) { yield return new WaitForSeconds(m_time); s += m_str[i].ToString(); m_text.text = s; i += 1; } StopAllCoroutines(); } /// <summary> /// 响应按钮 /// </summary> void OnTheClick() { StopAllCoroutines(); if (s != m_str) { m_text.text = m_str; } else { if (ES3.KeyExists(textIndex.ToString(), "0_0")) { PlayText(); } } }
原理很简单,就一个协程而已。我写了两个模式,一个是自动翻页,一个是按键翻页。配上audio,还真有那么点感觉。
可以看到我用的是EasySave3这个插件来做存储的,最近对移动端存储这块有点疑惑,希望能有大神指导一些。Q543109599 好人一生平安~