CraftedCart CraftedCart - 13 days ago 8
C# Question

Passing references (And Unity's WWW.progress) to Coroutines/IEnumerators

I've made a coroutine within C# using Unity 5 and I'd like to pass a reference to it. It didn't seem to work so I made a test script to try to isolate the following error.

error CS1623: Iterators cannot have ref or out parameters


Here's the test script:

using UnityEngine;
using System.Collections;

public class TEMP : MonoBehaviour {

// Use this for initialization
void Start () {
float var = 3.141f;
StartCoroutine ( test (ref var) );
}

IEnumerator test (ref float value) {
for (int i = 1; i <= 10; i++) {
Debug.Log (value);
yield return null;
}
}
}


In addition, on my actual script, I'm using Unity's WWW class to download something, and I also get this error when I pass www.progress as a reference:

A property or indexer 'UnityEngine.WWW.progress' may not be passed as 'ref' or 'out' parameter

Answer

Remove the ref from the function arguments.

// Use this for initialization
void Start () {
    float var = 3.141f;
    StartCoroutine ( test (var) );
}

IEnumerator test (float value) {
    for (int i = 1; i <= 10; i++) {
        Debug.Log (value);
        yield return null;
    }
}

Based on your requirement you could do something like below with an out parameter. I'm not exactly sure how you are intending to use these methods but I think you are getting the wrong idea about ref arguments and how they work.

class Program
{
    static void Main(string[] args)
    {
        float var = 3.14f;
        StartCoroutine(test(var), out var);

    }

    static IEnumerator test(float value)
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(value);
            yield return value + 1;
        }
    }

    static void StartCoroutine(IEnumerator test, out float update)
    {
        update = 0;
        while (test.MoveNext())
        {
            update++;
            Console.WriteLine("Executing..." + update);
        }
    }
}

However you are never going to be able to pass a ref or out parameter to the interator.