如何让我的Ui按钮在Unity中切换颜色?

时间:2015-09-28 04:13:33

标签: user-interface button unity3d colors

我只使用UI在Unity中进行基本的第三场比赛。对于要匹配的对象,我使用UI按钮并使对象具有不同的颜色。为了让对象切换宫殿我有一个方法来切换按钮的颜色。我的难点在于按下按钮调用方法。

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

public class match : MonoBehaviour {

public float time = 30.0f;
public float _score;
public GameObject pausePanel;
private Color[] colors = new Color[3];
//public Button[] buttons;
private Image[] image = new Image[16];
public Image im1;
public Image im2;
public Image im3;
public Image im4;
public Image im5;
public Image im6;
public Image im7;
public Image im8;
public Image im9;
public Image im10;
public Image im11;
public Image im12;
public Image im13;
public Image im14;
public Image im15;
public Image im16;
public Image b;
public Image c;
public Image temp;

void Start () {
    _score = 0.0f;
    colors [0] = Color.red;
    colors [1] = Color.blue;
    colors [2] = Color.green;
    image [0] = im1;
    image [1] = im2;
    image [2] = im3;
    image [3] = im4;
    image [4] = im5;
    image [5] = im6;
    image [6] = im7;
    image [7] = im8;
    image [8] = im9;
    image [9] = im10;
    image [10] = im11;
    image [11] = im12;
    image [12] = im13;
    image [13] = im14;
    image [14] = im15;
    image [15] = im16;
}

void Update () {

    time -= Time.deltaTime;

    if (time <= 0) {
        time = 0.0f;
    }

    if (time == 0 && _score == 0) {
        pausePanel.SetActive (true);
    }
    AssignColor (); 
}

void OnGUI()
{
    GUI.Box (new Rect (10, 10, 30, 20), "" + time.ToString ("0"));
    GUI.Box (new Rect (85, 410, 30, 20), "" + _score.ToString ("0"));
}

void AssignColor()
{
    foreach (Image i in image) {
        int colornum = Random.Range (0, colors.Length);
        if(i.color == Color.white){
            i.color = colors[colornum];
        }
    }

}

public void getButton(Image i)
{
    if (b == null) {
        b = i;
    } 
    else if (c == null) {
        c = i;
    }

    if (b != null && c != null) {
        Swap(b, c);
        b = null;
        c = null;
    }
}

void Swap(Image ac, Image bc)
{
    //Image temp;
    temp.color = ac.color;
    ac.color = bc.color;
    bc.color = temp.color;

}
}

我的Inspector中的所有按钮都能够激活getButton,并且按下按钮时图像b或图像C正在拍摄图像,但它们没有切换颜色。

1 个答案:

答案 0 :(得分:-1)

OnGUI()中,您可以使用GUI.color = Color.Blue;将之后的所有内容涂成蓝色。要使项目再次显示正常(例如,如果您只想为某种颜色的1个UI元素着色),请使用GUI.color = Color.White

void OnGUI()
{
    GUI.color = Color.Blue;// Tints everything hereafter in blue
    GUI.Box (new Rect (10, 10, 30, 20), "" + time.ToString ("0"));

    GUI.color = Color.White;// Tints everything hereafter normally
    GUI.Box (new Rect (85, 410, 30, 20), "" + _score.ToString ("0"));
}