A dialogue system I created uses a method called ReadLine() to type out the speaker’s text like a typewriter. This method takes a string for the speaker’s name, a string for the speaker’s text, and an integer index to keep track of the conversation every time a key is pushed. However, when the speaker’s name is null, the text does not get typed out when it is called for the first time. The problem seems to stem from the else-if statement within ReadLine(), but I am unable to figure out why as it has nothing to do with the speaker’s name. Any help would be appreciated.
Dialogue Script:
public class DialogueScript : MonoBehaviour
{
private Image dialogueBox;
private TextMeshProUGUI nameBox;
private TextMeshProUGUI textBox;
private float textSpeed = 0.05f;
private int textIndex;
//Reference to dialogue box:
void Start()
{
dialogueBox = GameObject.Find("Overlay").transform.GetChild(5).GetComponent<Image>();
nameBox = dialogueBox.transform.GetChild(0).GetComponent<TextMeshProUGUI>();
textBox = dialogueBox.transform.GetChild(1).GetComponent<TextMeshProUGUI>();
}
//Play dialogue:
void Update()
{
OpenDialogueBox();
ReadLine("Johnny", "I have a question!", 1);
ReadLine(null, "Answer the question?", 2);
ReadLine(null, "Are you sure?", 3);
ReadLine("Roderick", "Ask away.", 4);
CloseDialogueBox(5);
}
//Open dialogue box:
void OpenDialogueBox()
{
if (!dialogueBox.gameObject.activeSelf && Input.GetKeyDown(KeyCode.T))
{
dialogueBox.gameObject.SetActive(true);
nameBox.text = string.Empty;
textBox.text = string.Empty;
textIndex = 1;
}
}
//Close dialogue box:
void CloseDialogueBox(int closingIndex)
{
if (closingIndex == textIndex)
{
StopAllCoroutines();
dialogueBox.gameObject.SetActive(false);
}
}
//Types script to dialogue box:
void ReadLine(string name, string text, int num)
{
text = "\"" + text + "\"";
if (Input.GetKeyDown(KeyCode.T) && num == textIndex)
{
nameBox.text = name;
if (textBox.text == text)
{
textIndex++;
}
else if (textBox.text.Length < text.Length && textBox.text.Length > 0)
{
StopAllCoroutines();
textBox.text = text;
}
else
{
textBox.text = string.Empty;
StartCoroutine(TypeLine(name, text));
}
}
}
//Typewriter effect:
IEnumerator TypeLine(string name, string text)
{
foreach (char letter in text)
{
textBox.text += letter;
yield return new WaitForSeconds(textSpeed);
}
}
}