Unity/엔진프로그래밍

0415_좀비슈터 단계별 테스트 _ 자동발사

minquu 2021. 4. 15. 12:09
반응형

해야할것

 

자동으로 발사가 되는 총을 만들어야한다. (이펙트 연습)

- 이펙트가 나와야한다.

 

 

-----

 

0. 건 안에 이펙트 들을 넣어준다 (자식으로 넣어서 같이 움직이게 하려함)

 

 

1.AutoShooting를 할 스크립터를 만들어준다.

!★ 코루틴 연습 ★!

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shooting : MonoBehaviour
{
    public ParticleSystem eff1;
    public ParticleSystem eff2;
    public float cycle = 1f;

    public void AutoShoot()
    {
        StartCoroutine(this.AutoShootImpl());   
    }

    private IEnumerator AutoShootImpl()
    {
        while (true) {
            eff1.Play();
            eff2.Play();
            yield return new WaitForSeconds(cycle);
        }
    }
}
    public ParticleSystem eff1;
    public ParticleSystem eff2;
    public float cycle = 1f;

먼저 필요한 오브젝트를 퍼블릭으로 직접 받는다.

Cycle은 총이 나가는 주기 

 

  public void AutoShoot()
    {
        StartCoroutine(this.AutoShootImpl());   
    }

    private IEnumerator AutoShootImpl()
    {
        while (true) {
            eff1.Play();
            eff2.Play();
            yield return new WaitForSeconds(cycle);
        }
    }

★이 구조가 제일 중요함★

 

    public void AutoShoot()
    {
        StartCoroutine(this.AutoShootImpl());   
    }
    

위 메서드를 소환하면 코루틴이 시작되는 구조이다.

(다른 클래스나 내부에서 사용할 때는 코루틴을 직접 소환하지 안하고 이런식으로 사용한다.)

 

 private IEnumerator AutoShootImpl()
    {
        while (true) {
            eff1.Play();
            eff2.Play();
            yield return new WaitForSeconds(cycle);
        }
    }
    

위 함수는 코루틴 함수이다.

코루틴의 조건은 

첫번째, 반환 타입을 꼭 IEnumerator 값으로 받아야한다.

두번째, 꼭 안에는 하나 이상의 yield return 를 받아야한다.

 

위 함수는 

코루틴이 시작되면 (코루틴은 한번만 소환됌)

while문으로 계속 반복을 시킨다.

반복문을 들어오면 eff 이펙트를 플레이하고, 

WaitForSeconds (변수)  // 를 사용하여 변수값 만큼 쉬고 다음 프레임으로 넣어가는 구조로 되어있다.

 

 

 

 

 

---

 

 

 

반응형