본문 바로가기
Programming/Unity

[Unity] 유니티에서 Thread 사용 - UI 데이터 처리

by 타임박스 2019. 9. 27.
반응형

기본적으로 유니티는 멀티쓰레드 기반으로 제작되지 않았습니다.

하지만 유니티는 C# 기반 스크립트로 Thread를 사용할 수 있습니다.

무슨 말이지!?!

쉽게 표현하자면 유니티 API 즉 MonoBehaviour 기반으로 사용되는 API를 Thread에서 사용하게 되면  관련 Main Thread 에러 오류가 나타납니다.

can only be called from the main thread 에러 발생.

 

그럼 우린 어떻게 해야할까!?

보통 통신관련에서 Thread를 사용해야되는 경우가 많습니다.

서버 - 클라이언트(유니티) 로 제작할 경우

서버에서 무수히 많은 데이터를 클라이언트에게 보냅니다. 하지만 쓰레드를 쓰지 않고 데이터를 수신받고 처리하기는

속도가 따라가지 않습니다.

그래서 쓰레드의 역할은 통신 데이터 처리를 하고 큐나 스택등에 데이터를 담아야합니다.

그럼 메인 쓰레드에서 Update나 IEnumerator를 통해서 큐를 체크하여 Dequeue를 하고 UI에 데이터를 맵핑하면 됩니다.

 

- 샘플 코드 -

using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using UnityEngine.UI;

public class TEST : MonoBehaviour 
{
    private Thread thread;
    private Queue<string> queue = new Queue<string>();
    public Text textBox;

	// Use this for initialization
    void Start ()
    {
        thread = new Thread(Run);
        thread.Start();
    }
	
	// Update is called once per frame
    void Update ()
    {
        if(queue.Count > 0)
        {
            textBox.text = queue.Dequeue();  //여기서 UI 처리..
            Debug.Log(textBox.text);
        }
    }

    private void Run()
    {
        while(true)
        {
            string s = "test";
            queue.Enqueue(s);	//쓰레드는 처리될 데이터를 큐에 담기
            //textBox.text = s;  //여기서 UI 처리시 에러발생!!!!!
            Thread.Sleep(1000);
        }
    }

    private void OnApplicationQuit()
    {
        if (thread != null)
            thread.Abort();
    }
}
반응형

댓글