'2d unity level generator instantiating wrong position

I have been trying to make my own level generator, which generates a prefab with the correct sprite based on the color that is match in the small map that I made.

More specifically, I made this small map.

enter image description here

If one of the colors matches one of the colors that are found in a color array, it will instantiate a prefab with the correct sprite and so on for the other colors. So far it instantiates the objects with the correct sprites.

However this is what it looks like when I play the game.

enter image description here

And this is what it's suppose to look like

enter image description here

I don't know why it is doing this because based on my code,

public Texture2D needColors;
public Texture2D tiles;
public Texture2D level;
public GameObject tile;
public Transform parent;
public Color32[] colors;
public Sprite[] sprites;

void Start(){
    for(int x = 0; x < level.width; x++){
        for(int y = 0; y < level.height; y++){
            GenerateLevel(x, y);
        }
    }
}

void GenerateLevel(int x, int y){
    Color32 pixelColor = level.GetPixel(x, y);
    if(pixelColor.a == 0){
        return;
    }
    for(int i = 0; i < colors.Length; i++){
        if(pixelColor.Equals(colors[i])){
            Vector2 position = new Vector2(x, y);
            Instantiate(tile, position, Quaternion.identity, parent);
            tile.GetComponent<SpriteRenderer>().sprite = sprites[i];
        }
    }
}

it should be skipping the transparent pixels.

How can I do this correctly?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source