简体   繁体   中英

c# unity pause a for loop untill bool returns true

i have a for loop that loops through a class array instantiating a new player class and passing in a string(name).

public void createPlayers( int pInput)
{
    //holds name
    string temporaryString="defualt";
    players = new Player[pInput];
   

    for (int i = 0; i < pInput; ++i)
    {
       
        //PlayerTypesNameFunction()// this gets and returns a string to Temporary String
        //wait till function returns with true meaning player(i) has entered name

        players[i] = new Player(100,temporaryString);
        Debug.Log(players[i].m_sName);
    } 
        
    CurrentState = GameState.m_eQueueWeather;
    CallGameCurrentState();


}

I want it to call a function which gets the player to type a name and only continue for loop when that function finishes. changes a bool to true(bool gotInfo), the loop then continues to take the string which is returned and stored in temporaryString (string instatiated above) and assigns it to the new player in this line players[i] = new Player(100,temporaryString); .

Am I heading in the right direction or should I approach this problem differently? Thank you in advance

I would not suggest the infinite loop here. I would go for the yield return subrutine method that's explained here

Create the subrutine

 IEnumerator WaitForKeyDown(KeyCode keyCode)
 {
     while (!Input.GetKeyDown(keyCode))
         yield return null;
 }

Wait wherever you want

 yield return StartCoroutine(WaitForKeyDown(KeyCode.Return));

This will resume when the user presses enter. You can then check the input value and re-ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM