TIL(24-05-30) - 데미지 피격시 화면 붉게 깜빡임(Unity)

임재훈·2024년 5월 30일

Unity

목록 보기
14/20
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class DamageIndicator : MonoBehaviour
{
    public Image _image;
    public float flashSpeed;

    private Coroutine _coroutine;

    private void Start()
    {
        ...
    }

    private void Flash()
    {
        if(_coroutine != null)
        {
            StopCoroutine(_coroutine);
        }

        _image.enabled = true;
        _coroutine = StartCoroutine(FadeAway());
    }

    private IEnumerator FadeAway()
    {
        float starAlpha = 0.3f;
        float a = starAlpha;
        Color color = _image.color;

        while (a > 0.0f)
        {
            a -= (starAlpha / flashSpeed) * Time.deltaTime;
            color.a = a;
            _image.color = color;
            yield return null;
        }
        _image.enabled = false;
    }
}
  • _image: UI->Image 전체화면을 채우는 투명하고 붉은 이미지
  • flashSpeed: 깜빡이는 속도
  • Flash: 이미 실행중인 코루틴이 있으면 멈춘다. 이미지를 켜고 코루틴 실행
  • FadeAway: 이미지의 알파값을 조절하여 화면이 붉게 깜빡이는 것을 표현.
  • _image.color.a 로 바로 대입 연산이 안된다. 새로운 color를 생성해주고 color.a를 변경한 다음 대입.
profile
초심을 잃지 말자!

0개의 댓글