如何在Unity中使用选定颜色数组为图像着色?

时间:2016-01-31 21:20:56

标签: arrays image unity3d

我有一张图片,我试图设置一个随机颜色。

 public Color teamAColor;

 public void Start() {
     teamAColor = new Color (0, 1, 0, 1);

     Image scoreBoardRed = GameObject.Find ("ScoreBoardRed").GetComponent<Image> ();
    scoreBoardRed.color = teamAColor;
 }

这很好用。

 public Color teamAColor;

 public void Start() {
     teamAColor = new Color (Random.value, Random.value, Random.value, 1);
     Image scoreBoardRed = GameObject.Find ("ScoreBoardRed").GetComponent<Image> ();
    scoreBoardRed.color = teamAColor;
 }

这也可以。

public Color teamAColor;

public Color[] teamAColors = new Color[4];

public void Start() {
   teamAColor = teamAColors [Random.Range (0, teamAColors.Length)];
     Image scoreBoardRed = GameObject.Find ("ScoreBoardRed").GetComponent<Image> ();
    scoreBoardRed.color = teamAColor;

   {
        //Team A Colors
        teamAColors [0] = new Color (.10f, .35f, .75f, 1);
        teamAColors [1] = new Color (.37f, .19f, .58f, 1);
        teamAColors [2] = new Color (.32f, .01f, .02f, 1);
        teamAColors [3] = new Color (1f, .58f, .14f, 1);
    }
}

这不起作用。它不会引入任何颜色。奇怪的是我使用相同的代码为动画着色,这确实有效。我有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在您的开始代码中,您无法访问颜色,因为您还没有构建数组,您需要在访问之前构建数组,请尝试以下方法:

public Color teamAColor;
public Color[] teamAColors = new Color[4];

public void Start() {
    //Team A Colors
    teamAColors [0] = new Color (.10f, .35f, .75f, 1);
    teamAColors [1] = new Color (.37f, .19f, .58f, 1);
    teamAColors [2] = new Color (.32f, .01f, .02f, 1);
    teamAColors [3] = new Color (1f, .58f, .14f, 1);

    teamAColor = teamAColors [Random.Range (0, teamAColors.Length)];
    Image scoreBoardRed = GameObject.Find ("ScoreBoardRed").GetComponent<Image> ();
    scoreBoardRed.color = teamAColor;
}

但你也可以通过这样做初始化start函数之外的值(即给它们默认值):

public Color[] teamAColors = new Color[] {new Color (.10f, .35f, .75f, 1),
                                          new Color (.37f, .19f, .58f, 1),
                                          new Color (.32f, .01f, .02f, 1),
                                          new Color (1f, .58f, .14f, 1) };

而不是在Start()函数中指定值。

答案 1 :(得分:0)

我已经测试了你的代码,它对我有用。只需添加一些Debug.Log来解决问题。

public void Start() {
    teamAColor = teamAColors[Random.Range(0, teamAColors.Length)];
    Debug.Log("Selected color: " + teamAColor);
    Image scoreBoardRed = GameObject.Find("ScoreBoardRed").GetComponent<Image>();
    Debug.Log("Image object: " + scoreBoardRed);
    Debug.Log("Default Image color:" + scoreBoardRed.color);
    scoreBoardRed.color = teamAColor;
    Debug.Log("New Image color: " + scoreBoardRed.color);

   {
        //Team A Colors
        teamAColors [0] = new Color (.10f, .35f, .75f, 1);
        teamAColors [1] = new Color (.37f, .19f, .58f, 1);
        teamAColors [2] = new Color (.32f, .01f, .02f, 1);
        teamAColors [3] = new Color (1f, .58f, .14f, 1);
    }
}