[C#, 유니티] 코루틴 IEnumerable, IEnumerator

2022. 11. 7. 19:24코딩 2막 <C#개념편>/코딩 2막 <C#응용편>

728x90

0부터 100까지 짝수를 출력하고 싶다. 단 IEnumerable을 사용할 것

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
 
public class EvenNumberCollections : IEnumerable
{
 
    public List<int> collection = new List<int>();
 
    public void Add(int value)
    {
        if (value % 2 == 0)
            collection.Add(value);
        else
            Debug.LogError(value + "is not even number");
    }
 
    public IEnumerator GetEnumerator()
    {
        return new InOrderEnumerator(this);
    }
}
 
 
public class InOrderEnumerator : IEnumerator
{
    public object Current => current;
    public EvenNumberCollections evenNumberCollections;
 
 
    public int current;
    public int index = 0;
 
 
    public InOrderEnumerator(EvenNumberCollections inputCollection)
    {
        evenNumberCollections = inputCollection;
    }
 
    public bool MoveNext()
    {
        current = evenNumberCollections.collection[index];
        index++;
        if (index < evenNumberCollections.collection.Count)
            return true;
        else
            return false;
    }
 
    public void Reset()
    {
        index = 0;
    }
}
 
 
 
public class GameManager : MonoBehaviour
{
    public EvenNumberCollections evenNumbers = new EvenNumberCollections();
 
    private void Start()
    {
        for (int i = 0; i < 100; i++)
            evenNumbers.Add(i);
 
        foreach (int current in evenNumbers)
        {
            Debug.Log(current);
        }
    }
 
}
cs

공감해주셔서 감사합니다

728x90