Post

Unity(7)

Unity(7) UI


UI(User Interface):

  1. Canvas: UI를 배치하기 위한 영역으로 카메라 혹은 게임 화면에 UI를 랜더링 할 수 있다.
  2. 유니티 스크립트에서 UI의 기능을 사용하기 위해서는 ,using UnityEngine.UI를 사용해 패키지를 불러와야 한다.
  3. 비주얼 컴포넌트:
    • Text
    • Image
  4. 인터렉션 컴포넌트:
    • Button: 클릭 시 특정 함수 실행
    • Toggle: 두가지 설정 또는 함수를 전환하며 사용
    • Slider: 볼륨을 조졸 혹은 일정 구간 내의 값을 드래그로 조정
    • Scrollbar: 다양한 view에서 스크롤
    • InputField: 텍스트의 입력창

게임 화면에 아이템 수집 개수와 전체 아이템 개수 표시하기

  1. Hierarcy 창에서 우클릭 후, creat empty하여 빈 오브젝트 생성, 이름을 GameManager로 변경
  2. GameManager 오브젝트에 “GameManager” 스크립트 생성 후 추가해주기, gamemanager는 프로젝트에서 공통적으로 쓰인다.
  3. Hierarcy 창에서 우클릭 UI->Text 선택한다. 두개 만들어 준다.
  4. 이름을 current, total로 정해준다.
  5. text의 위치를 우측 상단에 위치하도록 조절 해준다. 아래 사진과 같이 하면 된다. screen</img>
  6. GameManger 스크립트에 아래의 코드 작성한다.

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class GameManager : MonoBehaviour
{
    public int totalItemCount;
    public TMP_Text totalCountText;//총 개수
    public TMP_Text currentCountText;// 습득 개수
    // Start is called before the first frame update
    void Awake()
    {
        totalCountText.text = "/ "+ totalItemCount.ToString(); //현재 스테이지의 총 아이템 개수
    }
    public void GetItem(int count){
        currentCountText.text = count.ToString();//현재 습득한 총 아이템 개수
    }
}
  1. 아래의 사진과 같이 “total”과 “current”를 넣어준다. screen</img>

  2. PlayerMovement를 아래의 코드로 수정해준다.

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement : MonoBehaviour
{   
    public float speed;
    public float jumpPower;
    public int itemCount; //획득한 item 개수
    bool isJump; //현재 점프 상대흫 나타내는 boolean, 땅에 닿고 있으면 false
    private Rigidbody rigid;
    public GameManager GM;
    // Start is called before the first frame update
    void Start()
    {   
        isJump = false;
        rigid = GetComponent<Rigidbody>();  //내컴포넌트에서 Rigidbody가져오기기
        itemCount = 0;
    }

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");//좌우 방향키
        float v = Input.GetAxisRaw("Vertical"); //상하 방향키

        rigid.AddForce(new Vector3(h,0,v) * speed, ForceMode.Impulse);// rigidbody에 힘을 전해주는 함수

        if(Input.GetKeyDown(KeyCode.Space) && !isJump){
            isJump = true;
            rigid.AddForce(new Vector3(0,jumpPower,0), ForceMode.Impulse);
        }
    }

    private void OnCollisionEnter(Collision other){
        if(other.gameObject.name == "floor"){
            isJump = false;
        }
    }

    private void OnTriggerEnter(Collider other){
        if(other.tag == "Item"){
            itemCount++;
            Destroy(other.gameObject);
            GM.GetItem(itemCount);
        }
    }
}

위와 같이 수정하고, 아래에 사진처럼 Player스크립트에 참조할 GameManger스크립트롤 넣어줘야한다.

screen</img>

이렇게 되면 이제 UI도 완성이된다. 감사합니다.

This post is licensed under CC BY 4.0 by the author.