0415 코루틴 사용해서 자동총쏘기 구현+코루틴 연습(fadeout)

2021. 4. 15. 15:24unity

 

using UnityEngine;

public class Gun : MonoBehaviour
{
    public ParticleSystem eff1;
    public ParticleSystem eff2;
    public float cycle = 1f;
    // Start is called before the first frame update

    public void AutoShoot() 
    {
        StartCoroutine(this.AutoShootImpl());
    }
    private IEnumerator AutoShootImpl() 
    {
        while (true) 
        {
            eff1.Play();
            eff2.Play();
            yield return new WaitForSeconds(0.1f);
        }
    }
}
using UnityEngine;
using UnityEngine.AI;

public class App : MonoBehaviour
{
    public Transform point;
    public NavMeshAgent agent;
    public Zombie zombie;
    public Gun GunEffect;
    // Start is called before the first frame update
    void Start()
    {
        this.zombie.Init();
        this.GunEffect.AutoShoot();

    }

코루틴이 약간 C#의 메서드 호출 방식으로 사용되는 것 같다...

 

using UnityEngine;
using UnityEngine.UI;

public class Fade : MonoBehaviour
{
    public Image fadeImage;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    public void FadeIn() 
    {
        Color startColor = fadeImage.color;

        for (int i = 0; i < 100; i++) 
        {
            startColor.a = startColor.a - 0.01f;
            fadeImage.color = startColor;
        }
    }
}

이렇게 호출할 경우 처리 속도가 너무 빨라서 바로 사라져 버림

 

using UnityEngine;
using UnityEngine.UI;

public class Fade : MonoBehaviour
{
    public Image fadeImage;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(FadeIn());
    }

    public IEnumerator FadeIn() 
    {
        Color startColor = fadeImage.color;

        for (int i = 0; i < 100; i++) 
        {
            startColor.a = startColor.a - 0.01f;
            fadeImage.color = startColor;

            yield return new WaitForSeconds(0.01f);

        }
    }
}

코루틴으로 메서드 실행 시 0.01초씩 딜레이를 주어 호출할시

위처럼 자연스럽게 페이드아웃/인이 가능해진다.

ansohxxn.github.io/unity%20lesson%201/chapter5-8/

'unity' 카테고리의 다른 글

0416 포스트 프로세싱/렌더링 파이프라인  (0) 2021.04.16
0415 Line Renderer  (0) 2021.04.15
0414 cinemachine/coroutine/IK pivot  (0) 2021.04.14
0412 쿠키런 달리기  (0) 2021.04.12
0409 캐릭터의 시야각과 공격범위 생성  (0) 2021.04.09