- Home /
Question by
JohnArthur · Jun 26, 2014 at 11:40 AM ·
c#dialogue
Auto-type text does not change to the next sentence
using UnityEngine;
using System.Collections;
//How to Use
//Add this script to GUITEXT
public class autoType : MonoBehaviour {
//speed
public float letterPause = 0.1f;
//public AudioClip sound;
//declare stanzas
string stanza,stanza2,stanza3,stanza4;
int where;
// Use this for initialization
void Start () {
//put sentences here
stanza = "THIS IS IT";
stanza2 = "new Message";
stanza3 = "hello World";
stanza4 = "next stanza";
}
void Update()
{
//start auto type
SetText(stanza);
//condition to change
if(where == 1)
{
stanza = "";
stanza = stanza2;
}
if(where == 2)
{
stanza = "";
stanza = stanza3;
}
if(where == 3)
{
stanza = "";
stanza = stanza4;
}
}
IEnumerator TypeText () {
foreach (char letter in stanza.ToCharArray()) {
guiText.text += letter;
yield return 0;
yield return new WaitForSeconds (letterPause);
}
//new stanza condition
where++;
Debug.Log (where);
}
void SetText(string text)
{
//StopCoroutine("TypeText");
stanza = text;
guiText.text = "";
StartCoroutine("TypeText");
}
}
As the title says, the text does not change to the next stanza.
Comment
Best Answer
Answer by gjf · Jun 26, 2014 at 02:26 PM
this will work, but it's not very friendly with the garbage collector - string concatenation, foreach, etc. but i'm guessing that getting it working is the most important to you right now ;)
using UnityEngine;
using System.Collections;
public class AutoType : MonoBehaviour
{
public float LetterPause = 0.1f;
private bool _textFinished;
private int _textIndex;
private string[] _stanzas;
public void Start()
{
_stanzas = new []{ "THIS IS IT", "new Message", "hello world", "next stanza", "you're welcome!" };
_textFinished = true;
_textIndex = -1;
}
public void Update()
{
if (_textFinished)
{
if (_textIndex++ >= (_stanzas.Length - 1))
{
_textIndex = 0;
}
SetText(_stanzas[_textIndex]);
}
}
private IEnumerator TypeText(float waitTime, string text)
{
_textFinished = false;
guiText.text = "";
foreach (var letter in text)
{
guiText.text += letter;
yield return new WaitForSeconds (waitTime);
}
_textFinished = true;
}
private void SetText(string text)
{
StartCoroutine(TypeText(LetterPause, text));
}
public void OnGUI()
{
GUI.Label(new Rect(10, 10, 150, 100), "Text:" + guiText.text);
}
}
Your answer
Follow this Question
Related Questions
C# Non-Static Member Rigidbody2D.MovePosition 1 Answer
Problem with player movements 1 Answer
How to make specific text in a string array Bold C# 2 Answers
Movement Script Help 1 Answer
C# Plane Detecting a Gameobject 1 Answer