Posts 유니티 에디터 GUI - 미끄러지는 On-Off 버튼
Post
Cancel

유니티 에디터 GUI - 미끄러지는 On-Off 버튼

Memo


2021_0826_Sliding_Button

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
bool onOff = true;
bool onOffMoving = false;
float onOffPos = 0f;
string onOffStr = "On";

private void DrawMovingOnOffButton()
{
    const float LEFT = 15f;
    const float RIGHT = 52f;
    const float WIDTH = 40f;
    const float HEIGHT = 20f;
    const float MOVE_SPEED = 1f;

    Rect rect = GUILayoutUtility.GetRect(1f, HEIGHT);

    Rect bgRect = new Rect(rect);
    bgRect.x = LEFT + 1f;
    bgRect.xMax = RIGHT + WIDTH - 2f;
    EditorGUI.DrawRect(bgRect, new Color(0.15f, 0.15f, 0.15f));

    rect.width = WIDTH;
    rect.x = onOffPos;

    Color col = GUI.backgroundColor;
    GUI.backgroundColor = Color.black;

    if (GUI.Button(rect, onOffStr))
    {
        onOffMoving = true;
    }

    if (!onOffMoving)
    {
        if (onOff)
        {
            onOffPos = LEFT;
            onOffStr = "On";
        }
        else
        {
            onOffPos = RIGHT;
            onOffStr = "Off";
        }
    }
    else
    {
        if (onOff)
        {
            if (onOffPos < RIGHT)
            {
                onOffPos += MOVE_SPEED;
                Repaint();

                if (onOffPos >= RIGHT)
                {
                    onOffMoving = false;
                    onOff = false;
                }
            }
        }
        else
        {
            if (onOffPos > LEFT)
            {
                onOffPos -= MOVE_SPEED;
                Repaint();

                if (onOffPos <= LEFT)
                {
                    onOffMoving = false;
                    onOff = true;
                }
            }
        }
    }

    GUI.backgroundColor = col;
}
This post is licensed under CC BY 4.0 by the author.