GetPixel returns alpha of 0 for all pixels of a texture2d.

I am using this code to create a basic level for my game:

public void Initialize(Texture2D map)
{
Debug.Log(“Initializing Map”);

    if (map.width > Max_Columns || map.height > Max_Rows) {

        throw (new Map_Too_Large_Exception("Map is too large.  Cannot be loaded."));
    }

    if (current_Level == null)
    {
        current_Level = new List<Block>();
    }
    else {

        current_Level.Clear();
    }

    for (int x = 0; x < map.width ; x++)
    {
        for (int y = 0; y < map.height; y++)
        {
            GenerateTile(x, -y, map);
        }
    }

    initialized = true;
}

void GenerateTile(int x, int y, Texture2D map) {

    Color32 pixelColor = map.GetPixel(x, y);

    **Debug.Log(pixelColor);**
    if (pixelColor.a == 0)
    {
        // The pixel is transparent ignore it!
        return;
    }

    foreach (Color_to_Prefab color in color_Map)
    {
        if (color.Color.Equals(pixelColor))
        {
            Vector2 position = new Vector2(x , y);
            GameObject go = Instantiate(color.Prefab, position, Quaternion.identity, transform);
            current_Level.Add(go.GetComponent<Block>());
        }
    }

    manager.Set_Level_Cleared(false);
}

The problem is my level is always empty. Because every pixel has an alpha of 0. I use the bolded debug.log to check the color. I have used paint.net and gimp to create textures and both produce the same problem. The alpha of colored pixels in both are set to 255 yet no matter what I try when imported to Unity checking the alpha always returns 0.,

Are you sure that you have marked your texture as “readable” in the texture importer settings? If it’s not readable you can not read any texture data because it’s not stored in PC RAM but only on the GPU.

Apart from that I highly recommend to not use GetPIxel but instead use GetPixels / GetPixels32 to read in the whole texture as a flattened array. This will be much faster with less overhead.

Likewise you should create a Dictionary<Color32, Block> to implement your “color_Map”. This has several advantages. A dictionary lookup has a time complexity of O(1) instead of O(n). Also you should store your prefab references in a Block variable instead of a GameObject variable. This will make Instantiate return the instantiated Block instance and you don’t need to call GetComponent afterwards.

Also note that in such tight loops with many iterations you should avoid method calls. In my example over here by removing unnecessary method calls the algorithm runs about 8 times faster in my case.