상세 컨텐츠

본문 제목

[Unity] 시간경과의 따른 로직 처리

Unity

by 메타샤워 2023. 7. 19. 15:31

본문

1. 특정 시간 경과 이후 특정 작업 반복 실행하기 
Coroutines으로 작업이 가능하지만 단순한 지연 이벤트를 처리하기는 Coroutines의 처리로직이 다소 복잡할 수 있다.
Time.deltaTime을 사용하는 방법
 float timeSpan;  //경과 시간을 갖는 변수
    float checkTime;  // 특정 시간을 갖는 변수
 
    void Start()
    {
        timeSpan = 0.0f;
        checkTime = 5.0f;  // 특정시간을 5초로 지정
    }
 
    void Update()
    {
        timeSpan += Time.deltaTime;  // 경과 시간을 계속 등록
        if (timeSpan > checkTime)  // 경과 시간이 특정 시간이 보다 커졋을 경우
        {
            /*
              Action!!!
            */
            timeSpan = 0;
        }
    }
 
2. 오브젝트가 생성된 이후 특정 시간이 경과 한뒤에 Destroy 시키기
화면에 오브젝트가 나타난뒤 몇초 이후 제거하려면 다음과 같은 코드를 사용하면 된다.
void Start()
{
      //5초 뒤에 gameObject 소멸
      Destroy(gameObject, 5);
}
 
3. Coroutine을 이용한 Action 지연 처리
using UnityEngine;
using System.Collections;
 
public class Wait : MonoBehaviour
{
    public bool check =true;
    private int i =0;
 
    void Update ()
    {
if(Input.GetKeyDown(KeyCode.A)&&check)
        {
   check = false;
           print("Inside" + i++);
           StartCoroutine(WaitForIt());
        }
    }
 
    IEnumerator WaitForIt()
    {
        yield return new WaitForSeconds(2.0f); 
        check=true;
    }
}
 
4 함수 지연 호출
 
public Rigidbody projectile;
void LaunchProjectile()
{
    Rigidbody instance = Instantiate(projectile);
    instance.velocity = Random.insideUnitSphere * 5;
 
    // CancelInvoke(“LaunchProjectile”); // 필요할 경루 Invoke 취소처리
}
 
void Start()
{
    Invoke("LaunchProjectile", 2); // 2초뒤 LaunchProjectile함수 호출
    InvokeRepeating("LaunchProjectile", 2, 0.3f); // 2초뒤 0.3초주기로 LaunchProjectile함수 반복 호출
}
언제 Coroutine을 사용해야 할까?
Coroutine은 Update 함수의 내용이 너무 복잡해지는걸 원치 않을때 유용하게 사용된다.
* 주의 : 여러개의 coroutine이 같은 변수를 수정하고자 하면 찾기 어려운 오류를 발생시킬수도 있다.

 

관련글 더보기