¡¡¼ÂÁõ¤ò´Þ¤á¤Æ¡¢Éü½¬¤ò¤ª¤³¤Ê¤Ã¤Æ½èÍý¤Î»È¤¤Êý¤ò³Ð¤¨¤Æ¤¤¤¤Þ¤·¤ç¤¦¡£
¡¡¤Þ¤º¤Ï²òÅúÎã¤ò¸«¤ëÁ°¤Ë¡¢¼«Ê¬¤Ç½èÍý¤ò¹Í¤¨¤Æ¤ß¤Æ¤¯¤À¤µ¤¤¡£
¤Þ¤¿²òÅúÎã¡¢¤È¤¢¤ë¤è¤¦¤Ë¡¢¤¢¤¯¤Þ¤Ç¤â¥µ¥ó¥×¥ë¤Î²òÅú¤Ç¤¹¡£¤Û¤«¤Ë¤â½ñ¤Êý¤Ï¤¢¤ê¤Þ¤¹¡£
¡¡£±¡¥¥³¥ë¡¼¥Á¥ó¤ÈÄ̾ï¤Î¥á¥½¥Ã¥É¤Î°ã¤¤¤Ï²¿¤Ç¤¹¤«¡©
¡¡¡¡¡¡¶ñÂÎŪ¤ÊÎã¤òµó¤²¤ÆÀâÌÀ¤·¤Æ¤¯¤À¤µ¤¤¡£
¡¡¢«¡¡¥¯¥ê¥Ã¥¯¤¹¤ë¤È²òÅúÎã¤òɽ¼¨¤·¤Þ¤¹¡£
¡¡¥³¥ë¡¼¥Á¥ó¤ÏÈóƱ´ü½èÍý¤ò¼Â¸½¤¹¤ë¤¿¤á¤ÎÆüì¤Ê¥á¥½¥Ã¥É¤Ç¤¢¤ê¡¢°ì»þÄä»ß¤·¤Æ¸å¤ÇºÆ³«¤Ç¤¤Þ¤¹¡£
Ä̾ï¤Î¥á¥½¥Ã¥É¤È¤Î¼ç¤Ê°ã¤¤¤Ï¡¢¥³¥ë¡¼¥Á¥óÆâ¤Çyield return¥¹¥Æ¡¼¥È¥á¥ó¥È¤ò»ÈÍѤǤ¤ëÅÀ¤Ç¤¹¡£¤³¤ì¤Ë¤è¤ê¡¢
ÂÔµ¡¤ä»þ´Ö¤Î·Ð²á¤òÀ©¸æ¤¹¤ë¤³¤È¤¬¤Ç¤¤Þ¤¹¡£
¡¡°Ê²¼¤Ï¶ñÂÎŪ¤ÊÎã¤Ç¤¹¡£
// Ä̾ï¤Î¥á¥½¥Ã¥É
void NormalMethod()
{
Debug.Log("Start");
Debug.Log("Middle");
Debug.Log("End");
}
// ¥³¥ë¡¼¥Á¥ó
IEnumerator CoroutineMethod()
{
Debug.Log("Start");
yield return new WaitForSeconds(1.0f);
Debug.Log("Middle");
yield return new WaitForSeconds(1.0f);
Debug.Log("End");
}
¡¡¾åµ¤ÎÎã¤Ç¤Ï¡¢Ä̾ï¤Î¥á¥½¥Ã¥É¤Ç¤Ï¤¹¤Ù¤Æ¤Î½èÍý¤¬°ìÅ٤˼¹Ԥµ¤ì¤Þ¤¹¤¬¡¢¥³¥ë¡¼¥Á¥ó¤Ç¤Ïyield return¥¹¥Æ¡¼¥È¥á¥ó¥È¤Ë¤è¤êÂÔµ¡¤¬ÁÞÆþ¤µ¤ì¡¢»þ´Öº¹¤Ç½èÍý¤¬¹Ô¤ï¤ì¤ëÅÀ¤¬°Û¤Ê¤ê¤Þ¤¹¡£
¡¡£²¡¥yield return null; ¤È yield return new WaitForSeconds(0); ¤Î°ã¤¤¤Ï²¿¤Ç¤¹¤«¡©
¡¡¡¡¡¡¤½¤ì¤¾¤ì¤Î°ã¤¤¤È¡¢»ÈÍѾìÌ̤òÀâÌÀ¤·¤Æ¤¯¤À¤µ¤¤¡£
¡¡¢«¡¡¥¯¥ê¥Ã¥¯¤¹¤ë¤È²òÅúÎã¤òɽ¼¨¤·¤Þ¤¹¡£
¡¡yield return null;¤Ï¡¢¼¡¤Î¥Õ¥ì¡¼¥à¤Þ¤Ç½èÍý¤ò°ì»þÄä»ß¤·¤Þ¤¹¡£°ìÈÌŪ¤Ë¡¢Ëè¥Õ¥ì¡¼¥à¹¹¿·¤¬É¬Íפʾì¹ç¤Ë»ÈÍѤµ¤ì¤Þ¤¹¡£
¡¡°ìÊý¡¢yield return new WaitForSeconds(0);¤Ï¡¢¼¡¤Î¥Õ¥ì¡¼¥à¤Þ¤ÇÂÔµ¡¤¹¤ë¤Î¤Ç¤Ï¤Ê¤¯¡¢¸½ºß¤Î¥Õ¥ì¡¼¥à¤Î½èÍý¤ò½ªÎ»¤·¡¢¼¡¤Î¥Õ¥ì¡¼¥à¤ÇºÆ³«¤·¤Þ¤¹¡£
¤Ä¤Þ¤ê¡¢¤Û¤Ü¨ºÂ¤Ë¼¡¤Î¥Õ¥ì¡¼¥à¤Ë°Ü¹Ô¤·¤Þ¤¹¡£
¡¡°Ê²¼¤Ï¤½¤ì¤¾¤ì¤Î»ÈÍÑÎã¤Ç¤¹¡£
IEnumerator ExampleCoroutine1()
{
yield return null; // ¼¡¤Î¥Õ¥ì¡¼¥à¤Þ¤ÇÂÔµ¡
Debug.Log("Next frame");
}
IEnumerator ExampleCoroutine2()
{
yield return new WaitForSeconds(0); // ¸½ºß¤Î¥Õ¥ì¡¼¥à¤Î½èÍý¤ò½ªÎ»¤·¡¢¼¡¤Î¥Õ¥ì¡¼¥à¤ÇºÆ³«
Debug.Log("Next frame");
}
¡¡yield return null;¤Ï¡¢Ëè¥Õ¥ì¡¼¥à¤Î¹¹¿·¤¬É¬Íפʾì¹ç¤Ë»ÈÍѤµ¤ì¡¢yield return new WaitForSeconds(0);¤Ï¡¢Â¨ºÂ¤Ë¼¡¤Î¥Õ¥ì¡¼¥à¤Ë°Ü¹Ô¤·¤¿¤¤¾ì¹ç¤Ë»ÈÍѤµ¤ì¤Þ¤¹¡£
¡¡£³¡¥¥³¥ë¡¼¥Á¥ó¤ò»È¤Ã¤Æ¡¢¥¥ã¥é¥¯¥¿¡¼¤¬»ØÄꤵ¤ì¤¿°ÌÃ֤˰ÜÆ°¤¹¤ë¥·¥¹¥Æ¥à¤òºîÀ®¤·¤Æ¤¯¤À¤µ¤¤¡£
¡¡¢«¡¡¥¯¥ê¥Ã¥¯¤¹¤ë¤È²òÅúÎã¤òɽ¼¨¤·¤Þ¤¹¡£
¡¡ºîÀ®Îã¤Ç¤¹¡£
using UnityEngine;
using System.Collections;
public class CharacterMovement : MonoBehaviour
{
public Transform targetPosition;
public float moveSpeed = 5.0f;
void Start()
{
StartCoroutine(MoveToTarget());
}
IEnumerator MoveToTarget()
{
while (Vector3.Distance(transform.position, targetPosition.position) > 0.1f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition.position, moveSpeed * Time.deltaTime);
yield return null;
}
Debug.Log("Reached target position!");
}
}
¡¡¾åµ¤Î¥¹¥¯¥ê¥×¥È¤Ç¤Ï¡¢¥¥ã¥é¥¯¥¿¡¼¤¬»ØÄꤵ¤ì¤¿°ÌÃÖ(targetPosition)¤Ë¸þ¤«¤Ã¤Æ°ÜÆ°¤¹¤ë¥·¥¹¥Æ¥à¤¬¼ÂÁõ¤µ¤ì¤Æ¤¤¤Þ¤¹¡£
MoveToTarget¥³¥ë¡¼¥Á¥ó¤Ï¡¢¥¥ã¥é¥¯¥¿¡¼¤¬ÌÜɸ°ÌÃÖ¤ËÅþ㤹¤ë¤Þ¤ÇËè¥Õ¥ì¡¼¥à°ÌÃÖ¤ò¹¹¿·¤·¡¢ÌÜɸ°ÌÃÖ¤ËÅþ㤷¤¿¤é¥á¥Ã¥»¡¼¥¸¤ò¥í¥°¤Ë½ÐÎϤ·¤Þ¤¹¡£
¡¡°Ê¾å¤Ë¤Ê¤ê¤Þ¤¹¡£
¡¡°ú¤Â³¤¡¢³Ø½¬¤ò¤¹¤¹¤á¤Þ¤·¤ç¤¦¡£
¡¡¡¡=>¡¡
¥³¥ë¡¼¥Á¥ó¤ÎÎý½¬ÌäÂê¢