简体   繁体   中英

How to add sprites in array C#?

I want to access game objects (sprites) in my code in an Array but I have no idea how to do that, I am new to C#.

This is my testing code, but I am not getting any values:

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;
        }
    }
}

Instead of using this keyword:

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

try to use countries[i]:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM