دستور StartCoroutine در یونیتی- coRoutine چیه؟ co routine چیست؟_اجرای یک دستور پس از چند ثانیه_تابع Invoke
شنبه, ۴ مهر ۱۳۹۴، ۱۱:۰۵ ب.ظ
منبع:gameover.blog.ir
روش اول:
Invoke("DoSomething", 10);//this will happen after 10 seconds
روش دوم:
//gameover.blog.ir
StartCoroutine(ExecuteAfterTime(10));
IEnumerator ExecuteAfterTime(float time)
{
yield return new WaitForSeconds(time);
// Code to execute after the delay
}
StartCoroutine(ExecuteAfterTime(10));
IEnumerator ExecuteAfterTime(float time)
{
yield return new WaitForSeconds(time);
// Code to execute after the delay
}
این تابع برای اجرای یک تابع بکار می ره.و اگه ازش استفاده کنیم با اسفاده از دستور yield می تونیم در هر نقطه از برنامه کار رو متوقف کنیم.وقتی coroutine ریسام میشه(resume به معنی ادامه دادن یا از سر گرفتن)دستور yield مقداری رو برگشت می ده. Coroutines در مواقعی که در حال مدلسازی رفتاری روی چند فریم هستیم،عالی است. Coroutine ها به طور مجازی سربار اجرایی(performance overhead) ندارند.تابع StartCoroutineمستقیما برگشت(return) داده می شود،همچنین می توانید نتیجه را yieldکرد.این باعث میشه که تابع صبر کنه تا زمانی که coroutine کارش تمام بشه بعدش دستورات بعدی رو از سر بگیره.
البته توی javascript نیازی به استفاده از StartCoroutine نیست.چون خود کامپایلر(compiler) این کار رو برای شما انجام میده.اما توی کد C sharp باید از StartCoroutine استفاده کنیم.
مثال یک :
using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { void Start() { print("Starting " + Time.time); StartCoroutine(WaitAndPrint(2.0F)); print("Before WaitAndPrint Finishes " + Time.time); } IEnumerator WaitAndPrint(float waitTime) { yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); } }
مثال دو:
using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { IEnumerator Start() { print("Starting " + Time.time); yield return StartCoroutine(WaitAndPrint(2.0F)); print("Done " + Time.time); } IEnumerator WaitAndPrint(float waitTime) { yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); } }
۹۴/۰۷/۰۴