如果在协程内部声明是如何工作的?

时间:2019-07-03 20:50:45

标签: c# unity3d coroutine

  1. 在此示例中,此协程将继续运行而不停止或否吗?
  2. “ test-1”将被打印多少次?

代码1:

public class TimePicker_Fragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    private static final String KEY_TIMEPICKER_TAG = "KEY_TIMEPICKER_TAG";

    /**
     *
     * @param timePickerTag the tag by which you can identify a TimePicker.  
     *             Will be set as tag to the TimePicker View in onTimeSet()
     * @return x
     */
    public static TimePicker_Fragment instance(String timePickerTag){
        TimePicker_Fragment fragment = new TimePicker_Fragment();
        Bundle b = new Bundle();
        b.putString(KEY_TIMEPICKER_TAG, timePickerTag);
        fragment.setArguments(b);
        return fragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        Context ctx = getContext();
        return new TimePickerDialog(ctx, this, hour, minute, DateFormat.is24HourFormat(ctx));
    }

    public void onTimeSet(TimePicker timePicker, int i, int i2){
        Bundle b = getArguments();
        assert b != null;
        timePicker.setTag(b.getString(KEY_TIMEPICKER_TAG));
        ((TimePickerDialog.OnTimeSetListener)getActivity()).onTimeSet(timePicker, i, i2);
    }
}

1 个答案:

答案 0 :(得分:4)

所以,这就是发生的情况:

我将一次分解您帖子中的代码:

  1. while (a){
    • 如果a为假,协程将立即退出(转到9),并且没有其他反应,否则,继续
  2. if(b){
    • 如果b为假,则转到7,否则,继续
  3. Debug.Log("test-1");
    • 在控制台上打印“ test-1”
  4. yield return new WaitForSeconds(1f);
    • 我们在这里创建一个对象,当该对象返回到处理协程(例如StartCoroutine())的Unity系统时,该函数的执行将被挂起并在以后返回。在这种情况下,请等待1秒(此值由当前Time.timeScale修改)。恢复执行后,请转到下一步:
  5. Debug.Log("test-2");
    • 在控制台上打印“ test-2”
  6. Debug.Log("test-3");
    • 在控制台上打印“ test-3”
  7. yield return break;
    • 在这里,我们告诉底层的Unity系统:(1)暂停执行该功能(yield)和(2)以后不再恢复该功能(break)。不要转到步骤8。
  8. } //end while(a)
    • 由于步骤7,我们从不返回while循环条件语句,也从不执行任何其他操作。
  9. } //end function
    • 函数终止

因此,如果ab都为真,那么回答您的问题“ test-1”将只打印一次。