👇 코루틴 사용법 - 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
StartCoroutine(LoopA());
}
IEnumerator LoopA()
{
for (int i = 0; i < 10; i++)
{
Debug.Log("LoopA 코루틴 실행");
yield return new WaitForSeconds(1f);
}
}
}
👇 코루틴 없이 딜레이 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public bool isDelay;
public float delayTime = 2f;
public float timer = 0f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (!isDelay)
{
isDelay = true;
Debug.Log("공격!");
}
else
{
Debug.Log("딜레이중..");
}
}
if (isDelay)
{
timer += Time.deltaTime;
if (timer >= delayTime)
{
timer = 0;
isDelay = false;
}
}
}
}
👇 코루틴 사용법 - 2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public bool isDelay = false;
public float delayTime = 2f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (!isDelay)
{
isDelay = true;
Debug.Log("공격!");
StartCoroutine(CountAttackDelay());
}
else
{
Debug.Log("딜레이중..");
}
}
}
IEnumerator CountAttackDelay()
{
yield return new WaitForSeconds(delayTime);
isDelay = false;
}
}
👇 코루틴 사용법 - 매개변수
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
StartCoroutine(TestCoroutine(10));
}
IEnumerator TestCoroutine(int count)
{
int i = 0;
while (i < count)
{
yield return null;
Debug.Log("코루틴 " + i);
i++;
}
}
}
[StopCoroutine]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
IEnumerator enumerator;
void Start()
{
enumerator = TestCoroutine();
StartCoroutine(enumerator);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StopCoroutine(enumerator);
}
}
IEnumerator TestCoroutine()
{
int i = 0;
while (true)
{
yield return null;
Debug.Log("코루틴 " + i);
i++;
}
}
}
[StopAllCoroutine]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
IEnumerator enumerator;
void Start()
{
enumerator = TestCoroutine();
StartCoroutine(enumerator);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StopAllCoroutines();
}
}
IEnumerator TestCoroutine()
{
int i = 0;
while (true)
{
yield return null;
Debug.Log("코루틴 " + i);
i++;
}
}
}
[yield break]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
StartCoroutine(ReturnCoroutine());
StartCoroutine(BreakCoroutine());
}
IEnumerator ReturnCoroutine()
{
Debug.Log("Return 1");
yield return null;
Debug.Log("Return 2");
}
IEnumerator BreakCoroutine()
{
Debug.Log("Break 1");
yield break; // 이때 코루틴 함수가 완전히 멈춘다
Debug.Log("Break 2"); // 실행시 Break 2 는 콘솔 화면에 보이지 않는다
}
}