x


WaitForSeconds in C# outside of start or awake

Good Day

I tried to understand the WaitForSeconds method trough the documentation and afterwards by looking here trough many questions but I still can't get it to work.

My setup is as follows:

  void FlipCardFaceUp(Card card_)
    {
       card_.isFaceUp = true;
       aCardsFlipped.Add(card_);
       if(aCardsFlipped.Count == 2)
       {
       playerCanClick = false;
       StartCoroutine(WaitASec(2));

       ((Card)aCardsFlipped[0]).isFaceUp = false;
       ((Card)aCardsFlipped[1]).isFaceUp = false;

       aCardsFlipped = new ArrayList();

       playerCanClick = true;
    }
}
IEnumerator WaitASec(float waitTime) {
    yield return new WaitForSeconds(waitTime);
   }

void OnGUI (){
       if(GUILayout.Button((Texture)Resources.Load(card.GetImage()), GUILayout.Width(cardW)))
         {
         FlipCardFaceUp(card);
         }
}

But It doesn't work, the game doesn't wait as if the function is not called. How exactly would I need to set it up so it will work?

If anyone can help me further with this I would appreciate it.

more ▼

asked May 27 '11 at 06:34 PM

Aranir gravatar image

Aranir
1 5 6 8

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

When you call use StartCoroutine without yielding, then it won't wait for the coroutine to finish, it will just launch the coroutine and continue on with the other instructions. There's no point to your WaitASec function, since it just calls WaitForSeconds and nothing else. You should remove that function, and just use yield WaitForSeconds directly in your FlipCardFaceUp function, which should be a coroutine.

more ▼

answered May 27 '11 at 06:45 PM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

Thank you so much I changed my code to:

IEnumerator FlipCardFaceUp(Card card) { card.isFaceUp = true; aCardsFlipped.Add(card_); if(aCardsFlipped.Count == 2) { playerCanClick = false; yield return new WaitForSeconds(2);

    ((Card)aCardsFlipped[0]).isFaceUp = false;
    ((Card)aCardsFlipped[1]).isFaceUp = false;

    aCardsFlipped = new ArrayList();

    playerCanClick = true;
}

}

void OnGUI (){ if(GUILayout.Button((Texture)Resources.Load(card.GetImage()), GUILayout.Width(cardW))) { StartCoroutine (FlipCardFaceUp(card)); } }

and it finally works correctly.

May 28 '11 at 11:09 AM Aranir
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4167
x170

asked: May 27 '11 at 06:34 PM

Seen: 1797 times

Last Updated: May 28 '11 at 11:09 AM