- Home /
Question by
winddarklj · Sep 26, 2014 at 07:03 AM ·
coroutinelambda
Coroutine Changed local variable behaviour in lambda, some confused
These are two script snippets:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TestScript : MonoBehaviour {
private delegate void XXXHandler();
private event XXXHandler xxxEvent = null;
private List<IEnumerator> list = new List<IEnumerator>();
// Use this for initialization
void Start () {
StartCoroutine(StartCall());
}
private void Call(XXXHandler handler)
{
xxxEvent += handler;
}
private IEnumerator StartCall()
{
for (int i = 0; i < 5; i++)
{
int index = i;
Call(() => { Debug.Log("i: " + index); });
}
xxxEvent();
yield return null;
}
// Update is called once per frame
void Update () {
}
}
The result here is : 4,4,4,4,4
Now I put code in StartCall() To Start(), others stay the same:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TestScript : MonoBehaviour {
private delegate void XXXHandler();
private event XXXHandler xxxEvent = null;
private List<IEnumerator> list = new List<IEnumerator>();
// Use this for initialization
void Start () {
for (int i = 0; i < 5; i++)
{
int index = i;
Call(() => { Debug.Log("i: " + index); });
}
xxxEvent();
}
private void Call(XXXHandler handler)
{
xxxEvent += handler;
}
private IEnumerator StartCall()
{
yield return null;
}
// Update is called once per frame
void Update () {
}
}
The result is: 0,1,2,3,4.
In my sense, the second result should be right. However, Coroutine changes everything here. I want to know why and what I need to do if I want use the local variable feature in Coroutine?
Comment
I've seen this issue, before. There seems to be some oddity with variable capture between coroutines and lambdas. It's definitely a bug.