[공부] 261021 - 유니티

강현구
∙∙조회 1

유니런 3회차

 

인게임 UI / 게임매니저와 재시작

csharp
    public static readonly string formatscore = $"SCORE: {0}";

    public TMP_Text scoreText;
    public GameObject gameOverUI;

    //외부에서 이 여부는 건들면 안되서
    public bool isGameOver{get; private set;}

    private int score = 0;
  • UI 선언
  • 게임오버 상태를 외부에서 수정 못하도록 프로퍼티, private set로 구현

 

csharp
    private void Update()
    {
        if(isGameOver && Input.GetKeyDown(KeyCode.Space))
        {
            Scene scene = SceneManager.GetActiveScene();
            SceneManager.LoadScene(scene.name);
        }

    }
  • 재시작 부분
  • 게임오버 상태인 동시에 스페이스 바를 누르면
    • SceneManager.GetActiveScene(); 으로 지금 룸 재시작

 


장애물 랜덤 스폰

csharp
using UnityEngine;

public class Platform : MonoBehaviour
{
    public GameObject[] obstacles;

    public float obstaclesRatio = 0.3f;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    private void OnEnable()
    {
        foreach (GameObject obstacle in obstacles)
        {
            //obstacle.SetActive(Random.value < obstaclesRatio);
            obstacle.SetActive(Random.Range(0f, 1f) < obstaclesRatio);
        }
    }




}

  • 하나의 플랫폼에 있는 장애물 생성을 랜덤으로 해주는 스크립트
  • public GameObject[] obstacles; 으로 장애물 랜덤설정
  • 플랫폼이 활성화될 때마다 obstacles 배열에 들어 있는 장애물들을 하나씩 확인해서, 각각 약 30%의 확률로 활성화하는 코드 - 왜? Ratio가 0.3이
  • Random.Range(0f, 1f) < obstaclesRatio <- 이 부분은 랜덤 숫자를 생성해서 기준값과 비교

예를 들어 obstaclesRatio가 0.3f라면 다음과 같아.

랜덤 숫자비교 결과활성화 여부
0.120.12 < 0.3 → 참활성화
0.280.28 < 0.3 → 참활성화
0.450.45 < 0.3 → 거짓비활성화
0.910.91 < 0.3 → 거짓비활성화

랜덤 숫자가 0.3보다 작으면 참(true), 그렇지 않으면 거짓(false)이 됨

 

 


플랫폼 생성 및 반복

 

 

 


땅바닥에 닿았을때만 점프되기

 

csharp
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.collider.tag == "Platform" && collision.contacts[0].normal.y > 0.7f)
        {
            //Debug.Log("닿았다");
            isGrounded = true;
            jumpCount = maxJumpCount;
            animator.SetBool("Grounded", true);
        }

    }
  •  

 


랜덤 타이밍 스폰

 

csharp
    public float intervalRange = 0.1f;// ?

    private float currentInterval;

//

//

    private void Update()
    {
        if(gameManager.isGameOver) //게임매니저에서 게임오버임이 나오면 중지
        {
            return;
        }

        spawnTimer += Time.deltaTime;
        if(spawnTimer > interval)
        {
            spawnTimer = 0f;
            currentInterval = interval + Random.Range(-intervalRange, intervalRange);
            Spawn();
        }

    }

 

 


랜덤 위치 스폰

csharp
    private void Spawn()
    {
        platforms[currentIndex].SetActive(false);

        Vector3 point = spawnPoint.position;
        point.y += Random.Range(-yRange, yRange);

        platforms[currentIndex].transform.position = point;
        platforms[currentIndex].SetActive(true);

        currentIndex = (currentIndex + 1) % platforms.Length;
    }

 

 


랜덤 타이밍 스폰

csharp
    private void Update()
    {
        if(gameManager.isGameOver) //게임매니저에서 게임오버임이 나오면 중지
        {
            return;
        }

        spawnTimer += Time.deltaTime;
        if(spawnTimer > currentInterval)
        {
            spawnTimer = 0f;
            currentInterval = interval + Random.Range(-intervalRange, intervalRange);
            Spawn();
        }

    }