- Home /
Question by
winddarklj · Sep 26, 2014 at 10:44 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
Your answer
Follow this Question
Related Questions
Lambdas, Singleton and Coroutine behaves different on Unity play and Android 1 Answer
How to shortcut a lambda expression through a function? 1 Answer
C# lambda call in for loop references to last object 3 Answers
Coroutine Changed local variable behaviour in lambda, some confused 0 Answers
Working projectile scripts do not work due to if condition 1 Answer