카테고리 없음

C# 2

openingsound 2020. 7. 15. 05:12

Action 과 Func

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Action & Func : delegate의 축약형태
using System;//Action은 system에 있음
 
public class Test : MonoBehaviour {
 
    delegate void MyDelegate<T1, T2>(T1 a, T2 b);
    MyDelegate<intstring> myDelegate;
    //delgate의 반환값이 void면 action 있으면 func
 
    Action<intint> myDelegate2;
 
    Func<intintstring> myDelegate3;//T1, T2, ret
 
    void Start()
    {
        myDelegate3 = (int a, int b) => { int sum = a + b; return sum + "이 리턴되었습니다."; };
 
        print(myDelegate3(35));//8 출력
    }
}
 
cs

예외 처리

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
using System;
public class Test : MonoBehaviour
{
    int a = 5;
    int b = 0;
    int c;
 
    void Start()
    {
        try
        {
            c = a / b;
        }
        catch(Exception ie)//관례상 ie로 씀
        {
            print(ie);
            b = 1;
            c = a / b;
        }
        finally
        {
            //오류가 실행되든 말든 마지막에 실행 되는 것
        }
 
        throw new Exception("일부러 오류를 발생 시킴"); 
    }
}
cs

코루틴

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
public class Test : MonoBehaviour {
 
    IEnumerator myCoroutine1;//coroutine1이 아님
 
    void Start()
    {
        myCoroutine1 = LoopA(1234);//파라미터 많으면 저장 가능
        StartCoroutine(myCoroutine1);
        StartCoroutine("LoopB");//문자열 처럼 성능이 더 구림
        StartCoroutine("LoopB"1);//맴버 변수 있으면 하나까지 넘길 수 있음
        StartCoroutine(Stoop());
    }
    #region Loop
    //루프 시작
    IEnumerator LoopA(int a,int b,int c,int d)
    {
        for(int i = 0; i < 100; i++)
        {
            print("i 의 값 = " + i);
            yield return new WaitForSeconds(1f);//1초 대기
        }
    }
    IEnumerator LoopB()
    {
        for (int j = 0; j < 100; j++)
        {
            print("j 의 값 = " + j);
            yield return null;//1프레임 대기
        }
    }
    #endregion Loop 
    //루프 끝
    IEnumerator Stoop()
    {
        yield return new WaitForSeconds(2f);
        StopCoroutine(myCoroutine1);
        yield return new WaitForSeconds(2f);
        StopCoroutine("LoopB");//문자열 처럼
 
        StopAllCoroutines(); //이 class에서 동작 중인 코루틴 모두 정지
    }
}
 
//이렇게 선언 해도 
 
  Coroutine myCoroutine1;
 
    void Start()
    {
        myCoroutine1 = StartCoroutine(LoopA());
        StartCoroutine(Stoop());
    }
cs