상세 컨텐츠

본문 제목

유니티 포탈타고 다음 씬으로 넘어가기, 씬전환시 페이드 인 아웃 효과

유니티/기능

by MJ_119 2024. 9. 25. 00:43

본문

- 유니티 포탈타고 다음 씬으로 넘어가기

 

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

public class Portal : MonoBehaviour
{
    // 포탈 이름을 나열한 열거형 Enum 선언 (A, B, C)
    enum PortalName
    {
        A, B, C
    }

    // 씬을 로드할 씬 번호 (초기값 -1로 설정)
    [SerializeField] int loadScene = -1;

    // 플레이어가 도착할 위치를 지정하는 Transform 변수
    [SerializeField] Transform SpawnPoint;

    // 포탈의 이름을 설정 (A, B, C 중 하나로 설정 가능)
    [SerializeField] PortalName portalName;

    // 플레이어가 포탈과 충돌할 때 호출되는 함수
    private void OnTriggerEnter(Collider other)
    {
        // 로드할 씬 번호가 -1일 경우 에러 메시지 출력
        if (loadScene == -1) { print("Check Scene number"); }

        // 충돌한 오브젝트가 플레이어라면 씬 전환 코루틴 실행
        if (other.CompareTag("Player"))
        {
            StartCoroutine(Transition());
        }
    }

    // 씬을 전환하고, 다른 포탈로 플레이어를 이동시키는 코루틴
    IEnumerator Transition()
    {
        // 포탈 오브젝트를 씬 전환 중 파괴하지 않도록 설정
        DontDestroyOnLoad(gameObject);

        // 씬을 비동기적으로 로드하고 완료될 때까지 대기
        yield return SceneManager.LoadSceneAsync(loadScene);

        // 다른 포탈을 찾아 플레이어의 위치를 갱신
        Portal otherPortal = GetOtherPortal();
        UpdatePlayerPosition(otherPortal);

        // 작업이 끝나면 포탈 오브젝트 파괴
        Destroy(gameObject);
    }

    // 플레이어의 위치를 다른 포탈의 SpawnPoint로 이동시키는 함수
    private void UpdatePlayerPosition(Portal otherPortal)
    {
        // 씬 내에서 태그가 "Player"인 오브젝트를 찾아 위치 및 회전값 갱신
        GameObject player = GameObject.FindWithTag("Player");
        player.transform.position = otherPortal.SpawnPoint.position;
        player.transform.rotation = otherPortal.SpawnPoint.rotation;
    }

    // 현재 씬에 있는 다른 포탈을 찾아 반환하는 함수
    private Portal GetOtherPortal()
    {
        // 씬 내의 모든 포탈을 검색
        foreach (Portal portal in FindObjectsOfType<Portal>())
        {
            // 자신을 제외한 다른 포탈을 찾기
            if (portal == this) continue;

            // 같은 이름을 가진 포탈만 선택
            if (portal.portalName != portalName) continue;

            // 일치하는 포탈을 찾으면 반환
            return portal;
        }

        // 다른 포탈을 찾지 못하면 null 반환
        return null;
    }
}

 

 

 

 

- 씬전환시 페이드 인 아웃 효과

 

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

public class FadeInOut : MonoBehaviour
{
    // CanvasGroup 컴포넌트를 참조할 변수 선언
    CanvasGroup canvasGroup;
    
    // 시작 시 호출되는 함수
    void Start()
    {
        // 현재 오브젝트에 있는 CanvasGroup 컴포넌트를 가져옴
        canvasGroup = GetComponent<CanvasGroup>();

        // 페이드 아웃-인 코루틴을 시작
        StartCoroutine(FadeOutIn());
    }

    // 페이드 아웃 후 페이드 인을 수행하는 코루틴 함수
    IEnumerator FadeOutIn()
    {
        // 1.5초 동안 페이드 아웃
        yield return FadeOut(1.5f);

        // 1초 동안 페이드 인
        yield return FadeIn(1f);
    }

    // 페이드 아웃 (투명도 증가) 처리 함수
    IEnumerator FadeOut(float time)
    {
        // 캔버스 그룹의 alpha 값이 1(완전 불투명)이 될 때까지 반복
        while (canvasGroup.alpha < 1)
        {
            // Time.deltaTime을 이용해 점진적으로 alpha 값을 증가시킴
            canvasGroup.alpha += Time.deltaTime / time;

            // 매 프레임마다 반복
            yield return null;
        }
    }

    // 페이드 인 (투명도 감소) 처리 함수
    IEnumerator FadeIn(float time)
    {
        // 캔버스 그룹의 alpha 값이 0(완전 투명)이 될 때까지 반복
        while (canvasGroup.alpha > 0)
        {
            // Time.deltaTime을 이용해 점진적으로 alpha 값을 감소시킴
            canvasGroup.alpha -= Time.deltaTime / time;

            // 매 프레임마다 반복
            yield return null;
        }
    }
}

 

 

 

관련글 더보기