How to find all the colors in a Texture2D, and saving them to an array

Sorry about the title, I wasn’t entirely sure how to phrase it, but basically I am trying to increase an index based on how many colors there are in a given Texture2D. To do this I have written

using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ProvinceMapGenerator : MonoBehaviour
{

public Texture2D provinceMap;

Color previousColor;
Color[ ] provinceColors = { new Color(0, 0, 0) };

int provinceIndex;

private void Start()
{
provinceColors = new Color[100];

GenerateProvinces();
}

public void GenerateProvinces()
{
// Check all pixels for different colors, and save each color
// Potential Bug, saying 54 when there is at least 59 colors...
for (int x = 0; x < provinceMap.width; x++)
{
for (int y = 0; y < provinceMap.height; y++)
{
// If the current pixel isn't the previous pixel, and the pixels aren't the same, increase the index
if (provinceMap.GetPixel(x, y) != previousColor && !provinceColors.Contains(provinceMap.GetPixel(x, y)))
{
// Save the color so that its not picked again
provinceColors[provinceIndex] = provinceMap.GetPixel(x, y);

provinceIndex++;
previousColor = provinceMap.GetPixel(x, y);

Debug.Log("Different Colors/Province Index: " + provinceIndex);
}
}
}
}

}

and this…somewhat works. It will count up to 54 which originally I thought was the answer, but in this case its actually 59. I’m not sure why its not.

In the if I try to see if the pixel is different, but not the same as other pixels, and if that is true, then save the new color to the provinceColor array, increase the index and set the previous color equal to the color that was just picked, and log the index. Again this prints 54, when the answer is 49. As for the Texture2D I am using,

Is the correct answer 59, or is it 49? You seemed to have said both in your post, which would give us a hint on what could be wrong.

As for the Texture2D you’re using, it looks like you were going to show us what it is but didn’t end up attaching it.

From what I can tell, the code should theoretically work fine, the only thing I noticed was that you initialized a new array of Colors for your provinceColors. Since Color is a struct, it should be pass by value and will fill your array with the default Color value (which I’m assuming is (0,0,0), but could be anything really). That means any pixel in your texture which is the same color as the default value wouldn’t increment your counter.

I’m also confused as to why you even have a previousColor value, as you keep track of every Color you’ve seen in an array. Is this just to be more efficient?