- Home /
How can I create an NPC Dialogue with UI Text?
HI, I already looked around for my problem but didn't find a solution.
Here's what I would like to do. While my character is running in my endless side-scroller game, I would like to tell the player a little story. To do this, I want to use UI Text elements which have animations on them to fade in and out. So on the screen appears a text, e.g., "Hello you." fades out again and then e.g. "Where are you going?" fade out again., and so on, and so on.
Here's my problem now I don't know what would be the right approach to have the sentence fly in on after another. So I tried trigger them with if statements (if (time == 5) say something, if (time == 8) says something else.) But this doesn't seem efficient. Then I tried to do it with an animator and stateMachineBehaviour. That worked a little. Maybe somebody could point me in the right direction?
It is a 3d game. But the dialog is shown with UI Text elements on screen space
Answer by Paricus · Dec 04, 2016 at 04:56 PM
use animations to control the fade in and fade out and create a library of text with an array that gets called every so often.
public string[] Story;
int i = 0;
public Animator anim;
public float readingTime = 5f;
public float storyInterval = 10f;
void Start()
{
StartCoroutine(CallText())
}
IENumerator CallText()
{
anim.setTrigger("ShowTextBox")
textBox.text = string[i];
i++;
yield return new WaitForSeconds(readingTime);
anim.setTrigger("CloseTextBox")
yield return new WaitForSeconds(storyInterval)
StartCoroutine(CallText())
}
Thanks. This looks promising. Can you tell me why you are calling StartCoroutine(CallText()) at the end of the IEnumerator CallText()? I haven't really used these before...
Hi, if you're going to program, you'll want to learn how to use coroutines. They're actually very simple to use. They essentially just run code alongside your current scripts.
In c# they allow you to create delays in between line of code, which will eli$$anonymous$$ate the need for a timer. by calling the coroutine at the end of the coroutine, it will repeat the code with the next text in the array.
Hey, thanks again. I just tried it and it works great. I will definitely take a look into coroutines.