Invoke

Invoke 사용하기

- 메서드가 x초 동안 지연된 이후 실행되게 할 수 있음

- 문법 : Invoke("함수 이름", 지연시간);

- 장점 : 사용하고 이해하기 쉬움

- 단점 : 문자열 참조로 함수 이름을 변경하거나 동적으로 할당할 때 불편함, 코루틴에 비해 성능이 떨어짐

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

public class CollisionHandler : MonoBehaviour
{
    [SerializeField]
    float levelLoadDelay = 1f;
    private void OnCollisionEnter(Collision collision)
    {
        switch (collision.gameObject.tag)
        {
            case "Friendly":
                Debug.Log("This thing is firendly");
                break;
            case "Finish":
                StartSuccessSequence();
                break;
            default:
                StartCrashSequence();
                break;
        }
    }

    // 추락 시퀀스 후 씬 전환
    void StartCrashSequence()
    {
        // 추락할 때 효과음 넣기
        // 추락할 때 파티클 넣기
        GetComponent<Movement>().enabled = false;
        Invoke("ReLoadLevel", levelLoadDelay);
    }

    void LoadNextLevel()
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        int nextSceneIndex = currentSceneIndex + 1;
        // SceneManager.sceneCountInBuildSettings 인덱스 총 갯수를 계산
        if (nextSceneIndex == SceneManager.sceneCountInBuildSettings)
        {
            nextSceneIndex = 0;
        }
        SceneManager.LoadScene(nextSceneIndex);
    }

    // 성공 시퀀스 후 씬 전환
    void StartSuccessSequence()
    {
        // 추락할 때 효과음 넣기
        // 추락할 때 파티클 넣기
        GetComponent<Movement>().enabled = false;
        Invoke("LoadNextLevel", levelLoadDelay);
    }

    void ReLoadLevel()
    {
        // 변수에 저장하는 이유는 나중에 봤을 때 코드를 해석할 시간을 줄이기 위해서이다.
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        // 현재 실행되고 있는 씬의 인덱스를 불러옴
        SceneManager.LoadScene(currentSceneIndex);
    }
}

도착 했을 때
부딪쳤을 때

 

함수명이 하는 기능을 나타내주도록 구분하는 게 중요한 것 같다

ex) StartCrashSequence는 충돌시 시퀀스에 관한 부분

ReloadLevel은 씬 재시작에 관한 부분

'유데미 강의 > C#과 Unity로 3D 게임 개발하기 : 부스트 프로젝트' 카테고리의 다른 글

bool 변수로 제어하기, 로켓 꾸미기  (0) 2022.08.23
오디오 클립  (0) 2022.08.23
SceneManager  (0) 2022.08.12
Switch  (0) 2022.08.12
유니티 오디오  (0) 2022.08.12

+ Recent posts