1

This is a message pertaining to C# in Unity, but I'm assuming general C# knowledge will apply.

Take the following code:

class myClass
{
    IEnumerator myEnumerator;
    public IEnumerator theEnumerator()
    {
        int i = 0;
        while (true)
        {
            Debug.Log(i++);
            yield return null;
        }
    }

    public void Update()
    {
        if (myEnumerator == null) { myEnumerator = theEnumerator(); }
        myEnumerator.MoveNext();
    }
}

If I instance that class, then call "Update" once per frame, I get the following output in the log:

0
1
2
3
4...

That works fine, however I want to implement some custom functionality in the IEnumerator itself. But if I create the following:

public class myIEnumerator : IEnumerator
{
    public int myCustValue;
    public void myCustFunction(){}
}

and then update the oringal class, replacing "IEnumerator" the "myIEnumerator", I get the following error:

The body of `myClass.theEnumerator()' cannot be an iterator block because `myIEnumerator ' is not an iterator interface type

What am I doing wrong here, and how can I make my own custom IEnumerator?

2
  • 5
    I think this is a compiler thing and the compiler supports only IEnumerable, IEnumerable<T>, IEnumerator, and IEnumerator<T>. Inheritance doesn't work for iterator blocks. Commented Dec 2, 2015 at 23:27
  • 1
    It's in the docs, "Iterator Methods and get Accessors The declaration of an iterator must meet the following requirements: The return type must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. The declaration can't have any ref or out parameters." Commented Dec 2, 2015 at 23:30

2 Answers 2

3

You can only use yield within a method whose return type is IEnumerator, IEnumerable, IEnumerator<T>, or IEnumerable<T>. You can't change the return type of the method to a type that implements one of those interfaces, that doesn't make sense.

The reason for this is that the C# compiler generates a special class that implements one of those 4 interfaces (actually it implements both IEnumerator and IEnumerable or the generic versions thereof) and an instance of that compiler generated class is what actually gets returned from the method. By changing the return type you're trying to say that the compiler will create an instance of your class that will do the enumeration. But it can't do that, because it doesn't actually know anything about your class (and in fact your class might not even enumerate correctly).

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that makes sense. Thanks for the explanation!
0

I'm not familiar with Unity but I think you have to implement the IEnumerator interface. The methods MoveNext()and Reset()are missing.

Have a look at the IEnumerator Interface

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.