# Calling functions that needs to be on update()

So I have a function DialogueRun() for a Dialogue System that changes the line on the dialogue box whenever you click. Which means it has to be in Update(). My test works so far but my next problem is how to make the whole dialogue box only appear whenever I click on a character.

I tried making the characters as buttons and it does make the dialogue box show up whenever clicked, but it won't change the dialogue lines because that function has to be in an update method.

I'm looking at OnMouseDown() right now but the result will be probably the same. Any ideas?

 public void DialogueRun()
{
dialogueBox.SetActive(true);
dialogue.text = textLine[nextLine];

if (nextLine < textLine.Length - 1)
{

if (Input.GetKeyDown(KeyCode.Mouse0))
{

nextLine += 1;
}
}
else
{            //counter++;
dialogueBox.SetActive(false);
return;
}

• This is not enough information. It's not clear how your current code works or why you think the Update() method doesn't work with "making the characters as buttons". Are your characters 2D or 3D? Are they part of a canvas or part of the world? – Kevin Dec 8 '20 at 19:31
• It's 2d. When I tried making it work with buttons I had to put it in the canvas but right now the characters are gameobjects with a Box Collider 2D. For the code, basically it's if counter is less than total lines, go to next line when clicked. – lover of the feet Dec 8 '20 at 19:43
• This looks ripe for a Coroutine. – DMGregory Dec 8 '20 at 20:20
• @Kevin added code to my post – lover of the feet Dec 8 '20 at 20:21

You can do something like this:

private bool dialogShowing;

void OnEnable() {
dialogShowing = false;
}

public void DialogueRun()
{
if (dialogShowing) return; //we don't want to show the dialog if it's already showing
dialogueBox.SetActive(true);
dialogue.text = textLine[nextLine];
}

//while the coroutine is running, check each frame to see if the user
//has clicked. if so, advance to the next line of dialog, or close the
//dialog if the user has reached the end
dialogShowing = true;
while (true) {
yield return null; //wait until the next frame
if (Input.GetKeyDown(KeyCode.Mouse0)) {
if (nextLine < textLine.Length - 1) {
nextLine ++;
dialogue.text = textLine[nextLine];
} else {
dialogueBox.SetActive(false);
dialogShowing = false;
yield break; //exit coroutine
}
}
}
}


When "DialogueRun" is called, we show the dialogueBox and start a coroutine that listens for user clicks. When the user clicks, the coroutine will advance the dialog to the next line, or close the dialog if the user reaches the end. This coroutine behaves similarly to an Update() function but unlike Update() it only runs when we need it to run.

• Thank you! This makes a lot of sense – lover of the feet Dec 8 '20 at 21:04