LoginSignup
1
1

More than 5 years have passed since last update.

[Unity] Coroutineに渡したIEnumaratorは再利用できない

Last updated at Posted at 2017-04-06

概要

IEnumeratorにはResetメソッドがある。
Coroutineに渡すIEnumeratorを再利用することができるのかという実験。
忘備録です。

環境

Unity5.5.2p4

結果

できません:smirk:
まぁ察しの通り。

内容

以下のコードをGameObjectにアタッチ。
uGUIのボタンのイベントにメソッドOnPressedButtonを関連付ける。

using UnityEngine;
using System.Collections;

public class Test2Coroutine : MonoBehaviour
{
    IEnumerator _iEnumerator;
    Coroutine _coroutine;

    private void Awake()
    {
        _iEnumerator = Loop();
    }

    IEnumerator Loop()
    {
        Debug.LogFormat("[LOOP] Start()");
        int i = 0;

        while(true)
        {
            i++;
            Debug.LogFormat("[LOOP] i:{0}", i);
            yield return null;
        }
    }

    public void OnPressedButton()
    {
        Debug.LogFormat("Pressed button.");
        _iEnumerator.Reset();

        if (_coroutine != null)
            StopCoroutine(_coroutine);

        _coroutine = StartCoroutine(_iEnumerator);
    }
}

ログの内容

Pressed button.
NotSupportedException: Operation is not supported.
at My.Test2Coroutine+<Loop>c__Iterator0.Reset () [0x00000]
at My.Test2Coroutine.OnPressedButton () [0x00017]
at UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) [0x00017]
at UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) [0x00056]
at UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) [0x0000e]
at UnityEngine.Events.UnityEvent.Invoke () [0x00008]
at UnityEngine.UI.Button.Press () [0x00022]
at UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) [0x00012]
at UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00008]
at UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) [0x00073]

ListなどのコレクションのIEnumeratorならできるかもしれないですね。
まぁ予想通り。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1