본문 바로가기

저장고

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

반응형

.




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

http://metashower.egloos.com/9666076



1. 특정 시간 경과 이후 특정 작업 반복 실행하기 
Coroutines으로 작업이 가능하지만 단순한 지연 이벤트를 처리하기는 Coroutines의 처리로직이 다소 복잡할 수 있다.
Time.deltaTime을 사용하는 방법
  1.     float timeSpan;  //경과 시간을 갖는 변수
  2.     float checkTime;  // 특정 시간을 갖는 변수
  3.  
  4.     void Start()
  5.     {
  6.         timeSpan = 0.0f;
  7.         checkTime = 5.0f;  // 특정시간을 5초로 지정
  8.     }
  9.  
  10.     void Update()
  11.     {
  12.         timeSpan += Time.deltaTime;  // 경과 시간을 계속 등록
  13.         if (timeSpan > checkTime)  // 경과 시간이 특정 시간이 보다 커졋을 경우
  14.         {
  15.             /*
  16.               Action!!!
  17.             */
  18.             timeSpan = 0;
  19.         }
  20.     }

2. 오브젝트가 생성된 이후 특정 시간이 경과 한뒤에 Destroy 시키기
화면에 오브젝트가 나타난뒤 몇초 이후 제거하려면 다음과 같은 코드를 사용하면 된다.
  1. void Start()
  2. {
  3.       //5초 뒤에 gameObject 소멸
  4.       Destroy(gameObject, 5);
  5. }


3. Coroutine을 이용한 Action 지연 처리
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Wait : MonoBehaviour
  5. {
  6.     public bool check =true;
  7.     private int i =0;
  8.  
  9.     void Update ()
  10.     {
  11. if(Input.GetKeyDown(KeyCode.A)&&check)
  12.         {
  13.    check = false;
  14.            print("Inside" + i++);
  15.            StartCoroutine(WaitForIt());
  16.         }
  17.     }
  18.  
  19.     IEnumerator WaitForIt()
  20.     {
  21.         yield return new WaitForSeconds(2.0f)
  22.         check=true;
  23.     }
  24. }

4 함수 지연 호출
  1. public Rigidbody projectile;
  2. void LaunchProjectile()
  3. {
  4.     Rigidbody instance = Instantiate(projectile);
  5.     instance.velocity = Random.insideUnitSphere * 5;
  6.  
  7.     // CancelInvoke(“LaunchProjectile”); // 필요할 경루 Invoke 취소처리
  8. }
  9.  
  10. void Start()
  11. {
  12.     Invoke("LaunchProjectile"2); // 2초뒤 LaunchProjectile함수 호출
  13.     InvokeRepeating("LaunchProjectile"20.3f); // 2초뒤 0.3초주기로 LaunchProjectile함수 반복 호출
  14. }

언제 Coroutine을 사용해야 할까?
Coroutine은 Update 함수의 내용이 너무 복잡해지는걸 원치 않을때 유용하게 사용된다.
* 주의 : 여러개의 coroutine이 같은 변수를 수정하고자 하면 찾기 어려운 오류를 발생시킬수도 있다.



. .

반응형