Hi everybody, so what I’m trying to accomplish here is setting up a text display system for the npcs in my game. Basically I have an array of text strings that i am iterating through individually and trying to display them one at a time only continuing after the player has pressed a button. I have looked at the coruoutine and yield functions but most of them are for a specific amount of time not a bool or something else. Here is a blerp from my code but basically what I need is someway to pause the loop without exiting it making it wait till a bool or something other than time has changed so it can go to the next string in the array without returning to the beginning and displaying the same text over and over again . This is in C# so if anyone could help me out that would be awesome!
Here's a simple script that loops through an array of Strings when a button is clicked.
It should be a good starting point.
/* an array of Strings - you can edit this in the Inspector */
var wordList : String [] = ["Funky", "Junky", "Spunky"];
/* rectangles for the GUI controls */
var buttonRect : Rect = Rect(100, 100, 100, 40);
var boxRect : Rect = Rect(100, 140, 100, 40);
/* an int that represents the current String in the array */
var currentWord : int = 0;
function OnGUI()
{
/* draw a button */
if ( GUI.Button(buttonRect, "Next word") ) {
/* go to the next word if button clicked */
currentWord ++;
/* go to zero when we hit the end of the list */
if ( currentWord >= wordList.length ) {
currentWord = 0;
}
}
/* display the current word in a box */
GUI.Box(boxRect, wordList[currentWord]);
}
I didn’t understand completely your script, but I suppose you want to stop after message.EnterText, wait until the user press some key, then continue the loop. If this is the case, you could do something like this:
bool running = false; // true when coroutine is running
void Update () {
if (!running){ // avoid starting multiple coroutines
CountTheTexts();
StartCoroutine(ChangeTextAsNeeded());
}
}
IEnumerator ChangeTextAsNeeded() // <- make this function a coroutine
{
running = true; // signal that coroutine started
if (npcscript.StartTalking == true && message.Text == null)
{
foreach (string text in textinput)
{
message.EnterText(text);
yield return 0; // assure at least one update cycle inside the loop
while (!Input.GetKeyDown("space")){ // wait for space key...
yield return 0; // but let Unity breath till next update
}
// continue the loop
if (text == textinput[textCount])
{
Debug.Log("we went through all responses");
npcscript.StartTalking = false;
}
}
}
running = false; // signal the coroutine has ended
}
Notice that the flag running was added to the code to avoid multiple coroutines being started: once one coroutine starts, it sets running and no other instances will be started until this one has finished.