ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Unity][2D] 버튼 만들기&연결하기
    프로그래밍/Unity 2021. 10. 26. 13:49
    728x90

    유니티에서 버튼을 만들고 싶었던 나..

     

    시도해본 것

    1. 버튼으로 만들고 싶은 이미지에 Button Component 추가하기 -> 안됨 잘모르겠음

    2. Hierarchy>UI>Button 추가 후 이미지 넣고 Script 추가하기 -> 됨!

     

    Button을 추가하면 Canvas 밑에 Button, 그리고 EventSystem 이 추가된다.

    EventSystem을 실수로 삭제하면 Button을 눌렀을 때 Event가 실행되지 않는다고 한다.

    Default상태에서는 button의 상태가 이상하므로..

    Canvas에서 Render Mode에서 Screen Space-Camera로 설정하고 Render Camera를 Hierarchy에서 Main Camara를 끌어온다.

    Render Mode에서 World Space로 바꿔주면 Transform 부분이 열리게 되는 것 같다.

    버튼의 그림을 설정하기 위해서 Image>Source Image에 그림을 끌어다 놓고

    눌렀을 때 Action을 표현하는 Script를 Button에 넣어준다.

    Text 변경은 Button 밑 화살표를 누르면 Text가 나오는데 Text부분에서 편집해주면 된다.

    // ======================================

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI; // <=필수

    public class button_Event : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {
            GetComponent<Button>().onClick.AddListener(MyAction);
        }

        void MyAction()
        {
            Debug.Log("Pressed");
        }
    }

    // ======================================

    버튼을 눌러주면? Log에 잘 나온다.

     

    ☆ Unity Console 창 키는 법:

    Window>General>Console

    ☆ AddListener:

    Runtime callback을 넣을 때 사용

    728x90
Designed by Tistory.