- Home /
How do I print each element of a string array separately to a UI text box
I am creating a game which involves a chat room. I want to store an array of strings which are basically dialogues from 2 characters. Every time I press Space bar I want to print each dialogue separately one after another. I feel like I am close but I cant figure out how to print induvial elements from the array, all I was able to do was print all elements at once which I don't want. Any help would be really great, thanks.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro;
public class DialogueManager : MonoBehaviour { public TextMeshProUGUI dialogueText;
[TextArea(3, 10)]
public string[] sentences;
protected void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartDialogue();
}
}
public void StartDialogue()
{
foreach (string sentence in sentences)
{
???????
}
}
}
Answer by TheIrishKraken · Oct 21, 2021 at 01:56 AM
Hi
Thank you so much for your answer. I applied your solution but I get this error every time I hit space.
I forgot the case when your sentences array may be empty.
Update your StartDialogue method and the error should vanish.
public void StartDialogue()
{
if (sentences.Lenght == 0)
{
return;
}
sentenceIndex = (sentenceIndex + 1) % sentences.Length;
dialogueText.SetText(sentences[sentenceIndex]);
}
Answer by Sztormu · Oct 20, 2021 at 10:02 AM
You need to access each array element separately.
Here's a solution with looping dialogue:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class DialogueManager : MonoBehaviour
{
private int sentenceIndex;
public TextMeshProUGUI dialogueText;
[TextArea(3, 10)]
public string[] sentences;
protected void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartDialogue();
}
}
public void StartDialogue()
{
sentenceIndex = (sentenceIndex + 1) % sentences.Length;
dialogueText.SetText(sentences[sentenceIndex]);
}
}
That worked! I would also like the string to appear line after line every time I hit space so it looks like below inside the dialogueText UI.
Player1: Hello
Player2: Hello
Player1: Nice day
Player2: Yup
Thanks so much for your help so far!