2013-03-12 9 views
5

Il nocciolo del mio codice è il seguente:Hai problemi refactoring un metodo IEnumerator con più rendimenti

// Play the first beat 
audio.PlayOneShot(beat); 

// Show 1st heartbeat border flash 
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.1f, currentStress); 
yield return new WaitForSeconds(0.1f); 
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.5f, 0); 

yield return new WaitForSeconds(interval); 

// Play the second beat 
audio.PlayOneShot(beat); 

// Show 2nd heartbeat border flash 
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.1f, currentStress); 
yield return new WaitForSeconds(0.1f); 
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.5f, 0); 

yield return new WaitForSeconds(interval * 2); 

Ora voglio dividere il codice sopra in un unico metodo IEnumerator con 2 chiamate.

Questo è ciò che mi si avvicinò con:

StartCoroutine(PlayBeat(currentStress, interval)); 
StartCoroutine(PlayBeat(currentStress, interval * 2)); 

// ... 

IEnumerator PlayBeat(float currentStress, float interval) 
{ 
    audio.PlayOneShot(beat); 

    TweenAlpha.Begin(heartbeatPanel.gameObject, 0.1f, currentStress); 
    yield return new WaitForSeconds(0.1f); 
    TweenAlpha.Begin(heartbeatPanel.gameObject, 0.5f, 0); 

    yield return new WaitForSeconds(interval); 
} 

Il problema di questo è che invece delle battute suonare con loro corretto intervallo, entrambe battute sembrava allo stesso tempo e perché ho queste chiamate nei un ciclo infinito, Unity si è schiantato perché gli intervalli non vengono considerati.

Qual è il modo migliore per estrarre i miei due blocchi ripetitivi di codice sopra in un singolo metodo IEnumerator?

+0

Il tuo codice attuale sembra buono (almeno, senza vedere 'StartCoroutine') - qual è il problema? –

+1

Puoi essere più specifico di "non funziona" quando descrivi il problema. – ChrisF

+0

Ho ragione a sentire i due ritmi contemporaneamente? – Kay

risposta

6

Le Coroutine di Unity3d possono essere annidate. Per aspettare una coroutine annidata devi cederla. Quindi la tua funzione PlayBeat va bene; devi solo avviarlo in modo che unity3d capisca che significa "aspetta fino al completo". Il tuo esempio potrebbe quindi apparire come segue:

yield return StartCoroutine(PlayBeat(currentStress, interval)); 
yield return StartCoroutine(PlayBeat(currentStress, interval * 2)); 

E 'inquietante come simile che guarda al asincrone C# 5 di/attendono. Ad un certo livello questo non è sorprendente dal momento che sono entrambe le statocachine "coroutine" trasformate dal compilatore - ma è ancora bello vedere la somiglianza.

+0

+1 Ho appena provato e funziona perfettamente. –

Problemi correlati