如何在数组C#中添加精灵?

时间:2017-05-01 11:43:52

标签: c# arrays unity3d sprite

我想在我的代码中以数组访问游戏对象(精灵),但我不知道该怎么做,我是C#的新手。

这是我的测试代码,但我没有得到任何值:

void Start()
{

    Sprite[] countries = Resources.LoadAll<Sprite>("MAPS");
    sr = GetComponent<SpriteRenderer>();
    names = new string[countries.Length];

    for (int i = 0; i < names.Length; i++)
    {
        names[i] = countries[i].name;
        //0 = red
        //1 = green
        if (UnityEngine.Random.Range(0, 2) == 0)
        {
            this.GetComponent<SpriteRenderer>().color = Color.red;
        }
        else
        {
            this.GetComponent<SpriteRenderer>().color = Color.green;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

而不是使用this关键字:

if (UnityEngine.Random.Range(0, 2) == 0)
{
    this.GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
    this.GetComponent<SpriteRenderer>().color = Color.green;
}

尝试使用国家[i]:

if (UnityEngine.Random.Range(0, 2) == 0)
{
    countries[i].GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
    countries[i].GetComponent<SpriteRenderer>().color = Color.green;
}