코루틴 함수란?
어떠한 작업을 처리하기 위해서 필요한 함수(메서드)를 호출하면, 해당 함수는 제 역할을 모두 수행한 후에 자신을
호출한 메인루틴(Main Routine)안의 코드의 다음 위치로 돌아가 프로그램 흐름이 이어지게 됨
만약 서브루틴(Sub Routine)이 반환하는 값을 가지고 있을 경우, 메인루틴(Main Routine)은 해당 반환값을 사용가능
이러한 현상을 서브루틴(SunRoutine)이라 칭한디.
Test9 Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test9 : MonoBehaviour
{
public Hero hero;
private void Start()
{
this.hero.OnMoveComplete = () =>
{
Debug.Log("이동완료");
};
}
void Update()
{
if (Input.GetMouseButtonUp(0))
// 왼쪽 마우스버튼을 클릭했을 때
// 스크린 좌표 => 월드좌표로 치환
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// 카메라의 태그 확인!
// 내가 클릭한 스크린좌표에 Ray 출력
// 카메라가 보는 방향으로 ray 생성
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red, 2f);
// ray의 위치에서 1000만큼의 길이의 빨간색ray를 2초동안 출력
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000))
// ray가 collider와 충돌했을 때 사용
{
if (hit.transform.tag == "Ground")
{
Debug.Log(hit.point);
this.hero.Move(hit.point);
}
}
}
}
}
Hero Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Hero : MonoBehaviour
{
public UnityAction OnMoveComplete;
// 델리게이트 변수 선언
private Coroutine routine;
public void Move(Vector3 tpos)
{
this.transform.LookAt(tpos);
// 이동할 때 gameObject를 tpos방향으로 바라보게 한다.
if (routine != null)
// routine이 null이 아니라면
{
this.StopCoroutine(this.routine);
// 코루틴 함수를 멈춘다
}
this.StartCoroutine(this.MoveImpl(tpos));
}
private IEnumerator MoveImpl(Vector3 tpos)
// 코루틴 함수
{
while(true)
{
this.transform.Translate(Vector3.forward * 1.0f * Time.deltaTime);
// 정면방향으로 1.0의 속도로 초단위로 이동
float dis = Vector3.Distance(tpos, this.transform.position);
if (dis < 0.5f)
{
break;
}
yield return null;
// 다음 프레임을 의미
// 코루틴함수 사용 시 반드시 선언!
}
this.OnMoveComplete();
}
}
※ 유니티 내에서 스크린 좌표 (0,0,0) 좌측하단
'Unity3D > 수업내용' 카테고리의 다른 글
2020.11.06 IntroScene 만들기 (0) | 2020.11.06 |
---|---|
2020.11.05 미니맵 생성 (0) | 2020.11.05 |
2020.11.03 스크린에서 클릭 시 해당 위치에 Ray 체크 (0) | 2020.11.03 |
2020.11.03 키보드 값에 따라 캐릭터 이동 및 회전 (0) | 2020.11.03 |
Unity 작업 Tip! (0) | 2020.10.30 |