본문 바로가기
UNITY/Unity Study

UI버튼 큐브 색 바꾸기

by GREEN나무 2023. 6. 22.
728x90

큐브하나 랜덤으로 색 바꾸기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CubeColorChanger : MonoBehaviour
{
    public GameObject cube; private Button button;

    private void Start()
    {
        button = GetComponent<Button>();
        button.onClick.AddListener(ChangeCubeColor);
    }

    private void ChangeCubeColor()
    {
        Renderer cubeRenderer = cube.GetComponent<Renderer>();
        cubeRenderer.material.color = GetRandomColor();

        ColorBlock colors = button.colors;
        colors.normalColor = GetRandomColor();
        button.colors = colors;
    }

    private Color GetRandomColor()
    {
        return new Color(Random.value, Random.value, Random.value);
    }
}

 

큐브 갯수제한없이 지정 색으로 바꾸기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MenuCubeColorChanger : MonoBehaviour
{
    public GameObject[] cubes; // 개수제한 없앰
    public Button button;
    public Color whiteColor;
    public Color blackColor;

    private bool allWhite = true;

    private void Start()
    {
        button.onClick.AddListener(ChangeCubeColors);
    }

    private void ChangeCubeColors()
    {
        allWhite = CheckAllWhite();

        Color newColor = allWhite ? blackColor : whiteColor;

        foreach (GameObject cube in cubes)
        {
            Renderer cubeRenderer = cube.GetComponent<Renderer>();
            cubeRenderer.material.color = newColor;
        }
    }

    private bool CheckAllWhite()
    {
        foreach (GameObject cube in cubes)
        {
            Renderer cubeRenderer = cube.GetComponent<Renderer>();
            if (cubeRenderer.material.color != whiteColor)
            {
                return false;
            }
        }

        return true;
    }
}

 

코드 하나로 버튼제어(캔버스에 넣기, 상세설정어려움 = 색변환 뺐음)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class AllButton : MonoBehaviour
{
    
    public void OnClickBag()
    {
        Debug.Log("가방");
    }

    public void OnClickMenu()
    {
        Debug.Log("메뉴");
    }

    public void OnClickCancel()
    {
        Debug.Log("취소"); // 게임 종료

#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else 
        Application.Quit();
#endif
    }

    public void OnClickSetting()
    {
        Debug.Log("설정");
    }

    public void OnClickExit()
    {
        Debug.Log("나가기");
    }