Skip to content

Instantly share code, notes, and snippets.

@gkagm2
Last active April 20, 2019 12:59
Show Gist options
  • Save gkagm2/ba74cdb8d9715f8d507ba6fbb99608fd to your computer and use it in GitHub Desktop.
Save gkagm2/ba74cdb8d9715f8d507ba6fbb99608fd to your computer and use it in GitHub Desktop.
웹 통신 할 떄의 Coroutine 사용법
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class csCoroutine2 : MonoBehaviour {
//비동기 작업이 끝날 때까지 댁시
public string url; //웹 주소를 저장할 스트링 변수를 퍼블릭으로 선언한다.
WWW www; //WWW 타입의 변수를 선언한다.
bool isDownloading = false;
IEnumerator Start() //Start 메서드를 코루틴 메서드로 변경한다.
{
www = new WWW(url); //웹 주소를 이용해 WWW 타입의 객체형을 만든다. 객체를 생성하면서 해당 주소의 내용을 가져오기 시잓한다.
isDownloading = true;
yield return www; //웹 주소의 내용을 다 가져올 때까지 코루틴의 실행을 멈춘다.
isDownloading = false;
Debug.Log("Download Completed!"); //웹 주소의 내용을 다 가져오면 로그를 출력한다.
Debug.Log(www.text);
}
// Update is called once per frame
void Update () {
if (isDownloading)
{
//다룬로드가 얼마나 진행되었는지를 나타낸다.(읽기전용)
Debug.Log(www.progress); //0과 1 사이의 값을 갖는다. 0은 다운로드가 하나도 되지 않은 상태, 1은 다운로드를 완료한 상태를 나타낸다.
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class csCoroutine3 : MonoBehaviour {
//비동기 작업이 끝날 때까지 대기
public string url; // 웹 주소를 저장할 스트링 변수를 퍼블릭으로 선언한다.
WWW www; // WWW 타입의 변수를 선언한다.
IEnumerator Start() // Start 메서드를 코루틴 메서드로 변경한다.
{
www = new WWW(url); // 웹 주소를 이용해 WWW 타입의 객체를 만든다. 객체를 생성하면서 해당 주소의 내용을 가져오기 시작한다.
StartCoroutine("CheckProgress"); // 웹의 데이터를 가져오는 과정을 살펴보기 위해서 또 다른 코루틴 메서드를 호출한다.
yield return www; // 웹 주소의 내용을 다 가져올 때까지 Start 코루틴의 실행을 멈춘다.
Debug.Log("Download Completed!"); //웹 주소의 내용을 다 가져오면 로그를 출력한다.
}
IEnumerator CheckProgress() //웹의 데이터를 가져오는 과정을 살펴보기 위한 코루틴이다.
{
Debug.Log("A: " + www.progress);
while(!www.isDone) // 웹의 데이터를 다 가져왔는지 체크한다.
{
yield return new WaitForSeconds(0.5f); // 데이터를 다 가져오면 0.5 초 대기한다.
Debug.Log("B: " + www.progress); // www 변수의 상태를 출력한다.
}
}
// Update is called once per frame
void Update () {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment