12.16 UI 버튼 만들기

C#/실습 2019. 12. 16. 17:04

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Title : MonoBehaviour
{
    enum eMenuType { Items, Shop, Message, Mission, Ranking, Settings};
    public UIButtonMenu[] arrBtnMenu;
    public Sprite[] sprites;
    public string[] btnMenuNames;
    // Start is called before the first frame update
    void Start()
    {                
        for(int i = 0; i<this.arrBtnMenu.Length; i++)
        {
            eMenuType menus = (eMenuType)i;
            this.arrBtnMenu[i].Init(menus.ToString(),sprites[i]);
            Button btn = arrBtnMenu[i].gameObject.transform.GetChild(1).GetComponent<Button>();
            btn.onClick.AddListener(() =>
            {
                Debug.LogFormat("selected Menu: {0}, {1} i: {2}", menus.ToString(), (int)menus);
            });
            
        }    
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButtonMenu : MonoBehaviour
{
    public Image icon;
    public Text textBtnName;
    public Button btn;
 
    public void Init(string btnName, Sprite spIcon)
    {
        this.textBtnName.text = btnName;
        this.icon.sprite = spIcon;
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UISelectedButton : MonoBehaviour
{
    public Button btn;
    public System.Action Onselected;
    public Text text;
    void Start()
    {        
        this.btn.onClick.AddListener(() =>
        {
            this.Onselected();
        });
    }
    public void Init(string text)
    {
        this.gameObject.transform.GetChild(1).gameObject.SetActive(false);
        this.text.text = text;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

Horizontal LayOut Group 컴포넌트를 이용해 더욱 쉽게 정렬을 할 수 있었다.

 

: