profile image

L o a d i n g . . .

article thumbnail image
Published 2020. 9. 21. 02:56
반응형

Button Event

Canvas의 Render Mode를 변경하면 다른 방식으로 출력할 수 있다. Screen Space - Overlay는 가상의 카메라가 찍고 있는다고 생각하면 편하다.

 

Button이 눌렸을 때 실행될 함수는 Button의 On Click()에 등록하면 된다.

UI 같은 경우, 해당 UI를 눌렀을 때 본인이 아니라 다른 오브젝트(플레이어, 다른 UI 등)를 동작하게끔 구현해야 할 수도 있기 때문에 Object를 선택하는 칸 또한 존재한다.

 

Canvas를 하나의 Prefab으로 저장해서 사용하면 된다.

 

부모 오브젝트에 사용할 Script를 붙이고, 부모 오브젝트를 Object에 끌어다 놓는다. 그리고 Script 내에서 public으로 선언한 함수를 지정해 주면 된다.

 

UI 버튼을 클릭했을 때, 플레이어가 움직이지 않게 하기 위해서 Input Manager에 해당 코드를 추가한다.

if (EventSystem.current.IsPointerOverGameObject())
    return;

 

상점에서 아이템 리스트를 보고, 아이템을 고르면 확인 메시지가 뜨고, 다이아가 부족하다고 하면 구매하시겠습니까? 이런 식으로 연속적인 팝업이 뜨게 된다. 이렇게 어떤 팝업이 먼저 뜰지를 설정하는 것이 바로 Sort Order이다.

큰 규모의 게임은 이렇게 구현할 경우, 하나하나씩 툴로 관리하기가 어렵다.
=> 코드에서 작업할 수 있다!

 

 

UI 자동화

Util 스크립트에서 오브젝트를 찾는 함수를 만들어 사용한다.

 

Event System: UI와 이벤트를 연동하기 위해서 활용해야 한다.

사용하기 위해서는 Event System의 Interface를 상속받아서 각 기능을 구현해야 한다.

 

public class UI_EventHandler : MonoBehaviour, IBeginDragHandler, IDragHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = eventData.position;
        Debug.Log("OnDrag");
    }
}

 

Rect Transform은 Transform을 상속받고 있기 때문에, 일반 오브젝트처럼 transform에 접근해서 작업할 수 있다.

 

public static T GetOrAddComponent<T>(GameObject go) where T : UnityEngine.Component
{
    T component = go.GetComponent<T>();
    if (component == null)
        component = go.AddComponent<T>();

    return component;
}

컴포넌트를 찾아오거나, 없다면 새로 추가하는 기능은 자주 사용하는 패턴이기 때문에 Util 함수로 쁩는다.

 

public static void AddUIEvent(this GameObject go, Action<PointerEventData> action, Define.UIEvent type = Define.UIEvent.Click)
{
    UI_Base.AddUIEvent(go, action, type);
}
private void Start()
{
    Bind<Button>(typeof(Buttons));
    Bind<Text>(typeof(Texts));
    Bind<GameObject>(typeof(GameObjects));
    Bind<Image>(typeof(Images));

    // Extension method를 이용한 방법
    Get<Button>((int)Buttons.PointButton).gameObject.AddUIEvent(OnButtonClicked);

    GameObject go = GetImage((int)Images.ItemIcon).gameObject;
    AddUIEvent(go, (PointerEventData data) => { go.gameObject.transform.position = data.position; }, Define.UIEvent.Drag);
}

 

 

UI Manager

팝업 관리를 위해 UI Manager를 만들어 사용한다.

경험치 창이나 체력 창 같은 건 고정으로 되어 있고, 변화가 일어나지 않는다.
=> 팝업용 UI/일반 UI로 나누어 관리해야 한다.

 

Image의 Alpha 값을 0으로 해 놓고 Raycast Target을 체크해 놓으면, 해당 UI가 팝업 처리 됐을 때 뒤에 있는 UI에 클릭 이벤트가 가지 않게끔 구현할 수 있다. 단, 순서에 유의한다.

 

 

인벤토리 실습

UI 오브젝트의 경우, 실제 Hierarchy에 생성해서 살펴보면 어떤 용도로 사용하는지 쉽게 알 수 있다.

docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIReference.html

 

UI Reference | Unity UI | 1.0.0

UI Reference This section goes into more depth about Unity’s UI features.

docs.unity3d.com

 

Image와 Panel은 기본 값만 다르고, 동일한 Image Component를 사용한다.

인벤토리처럼 특정 오브젝트들을 일정하게 정렬해야 할 때, Layout Group Component를 사용한다.

 

반응형
복사했습니다!