[Unity][Thread] Thread Ninja by

31
Aug
0

“Unity’s coroutine is great, but it’s not a real thread. And a background thread is not allowed to access Unity’s API.” ผู้สร้าง Thread Ninja ได้กล่าวไว้

จะสังเกตุได้ว่า หากมีการคำนวนหนักๆ ถึงแม้ว่าเราจะจับมันไปอยู่ใน Coroutine แล้วก็ตาม มันก็ยังส่งผลให้เกมของเราเกิดอาการกระตุก หรือ เฟรมเรต ตกลงไป นั่นเป็นเพราะว่าแท้จริงแล้ว Coroutine ของ Unity นั้น ไม่ใช่ Thread ที่แท้จริงนั่นเอง

วันนี้ผมจึงมานำเสนอ Thread Ninja ที่จะทำให้ชึวิตเราง่ายขึ้นมากกกกกในการเขียนโปรแกรมแบบ Multithread บน Unity ครับ

เจ้า Thread Ninja นี้มีวิธีใช้ง่ายแสนง่ายครับ

  • ก่อนอื่น หาโหลด Package Thread Ninja ได้จาก Unity Asset Store ครับ แล้วก็ Import เข้าไปใน Project เรา เราก็ได้จะได้ โฟลเดอร์ชื่อ CielaSpike มาอยู่ใน Project ครับ
  • ก่อนใช้ต้อง using CielaSpike; ก่อนครับ
  • ใช้ Thread Ninja ให้เหมือนใช้ Coroutine ธรรมดาเลยครับ คือปกติ เรียก Coroutine แบบนี้ใช่ไหมครับ StartCoroutine(Func()); แค่เปลี่ยนไปเรียกแบบนี้ this.StartCoroutineAsync(Func()); จบครับ
  • เปลี่ยนจาก yield return StartCoroutine(Func()); เป็น
    Task task; this.StartCoroutineAsync(YourRoutine(), out task); // do sth else. // wait task to complete. yield return StartCoroutine(task.Wait()); // task has done. if (task.State == TaskState.Error) { // … }
  • ข้อสำคัญครับ “background thread is not allowed to access Unity’s API” ครับ ดังนั้นถ้าเราอยากใช้ Unity API ในระหว่างที่มันอยู่ใน background thread เราก็ทำอย่างนี้ครับ
    IEnumerator YourAsyncRoutine() { // now on background;
    yield return Ninja.JumpToUnity; //=> here’s our ninja, following code runs on main thread.
    Destory(gameObject); // OK!
    yield return Ninja.JumpBack; //=> go back to background.
    // continue doing some heavy computing without blocking the main thread. // … }

 

ง่าาาายมากใช่ไหม เย่ๆ มาทำ Multithread Programming กันเถอะ

Enjoy this article?

Consider subscribing to our RSS feed!

ไม่มีความเห็น

ยังไม่มีความเห็น

ใส่ความเห็น

RSS feed for comments on this post