코루틴(Coroutine)
https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity3.html
https://docs.unity3d.com/kr/530/Manual/Coroutines.html
연습코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TestMain : MonoBehaviour
{
public Image image;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void Fade()
{
for (float a = 1; a >= 0; a -= 0.1f)
{
Color color = image.color;
color.a = a;
Debug.Log(a);
image.color = color;
}
}
//코루틴 함수
IEnumerator FadeRoutine()
{
for (float a = 1; a >= 0; a -= 0.01f)
{
Color color = image.color;
color.a = a;
Debug.Log(a);
image.color = color;
yield return null; //1프레임을 건너뛴다
}
for (float a = 0; a <= 1; a += 0.01f)
{
Color color = image.color;
color.a = a;
Debug.Log(a);
image.color = color;
yield return null; //1프레임을 건너뛴다
}
//1프레임 건너뜀
//yield return null; //여러번 사용 가능
//1프레임 건너뜀
//yield return null; //여러번 사용 가능
//1프레임 건너뜀
//yield return null; //여러번 사용 가능
}
//코루틴 필드 //코루틴을 여러번 클릭하면 코루틴이 여러번 복사됨을 방지
private Coroutine fadeRoutine;
public void OnClickButton()
{
Debug.Log("Click");
if (this.fadeRoutine == null)
{
this.StartCoroutine(this.FadeRoutine());
}
this.fadeRoutine = null;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TestMain : MonoBehaviour
{
public Image image;
//코루틴 함수
IEnumerator WaitForSec(float sec, System.Action callback)
{
yield return new WaitForSeconds(sec);
Debug.Log("Hello World!");
callback();
}
public void OnClickButton()
{
Debug.Log("click");
StartCoroutine(this.WaitForSec(3f, () => {
Debug.Log("Callback Complete!");
}));
}
}
yield return null; //1프레임을 건너뛴다
yield return이 null라고 null이 반환되는 것은아님
코루틴이 끝나면 코루틴 인스턴스가 반환된다.
코루틴의 종료를 알고 싶다면 bool타입의 변수를 선언하고
코루틴 마지막 라인에서 bool타입의 변수에 true 또는 false를 할당하고
할당된 bool타입의 값으로 확인가능
private bool CR_running;
void InvokeMyCoroutine()
{
StartCoroutine("Coroutine");
}
IEnumerator Coroutine()
{
CR_running = true;
//do Stuff
yield return //Whatever you want
CR_running = false;
}
// As long as you a within this scope you can just do :
void AnotherFunction()
{
if (CR_running)
{
// Do some other stuff;
}
}
코루틴 변수에 코루틴을 넣어 null이 아니라면 실행중
스탑코루틴 사용
'Unity > 게임 엔진 응용 프로그래밍' 카테고리의 다른 글
| Vertical 2D Shooting 09 : 코루틴으로 무적시간 구현 (0) | 2021.10.15 |
|---|---|
| Vertical 2D Shooting 08 : 코인 이이템 드롭 (0) | 2021.10.15 |
| Vertical 2D Shooting 07 : UI 일부 구현 (점수, 생명) (0) | 2021.10.14 |
| Vertical 2D Shooting 06 : 적기 자동생성, 피격 애니메이션 (0) | 2021.10.14 |
| Vertical 2D Shooting 05 : 적기 파괴 (0) | 2021.10.13 |