Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active January 17, 2023 09:47
Show Gist options
  • Select an option

  • Save unitycoder/c26ff19e29034603eb0a0f9dd6d703b5 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/c26ff19e29034603eb0a0f9dd6d703b5 to your computer and use it in GitHub Desktop.
c# generate unique colors for integer UID numbers
sing UnityEngine;
class Example
{
public static Color GetColorForUid(int uid)
{
// You can use the mod operator to map the UID to a value between 0 and 1.
float r = (float)(uid % 256) / 256.0f;
float g = (float)((uid / 256) % 256) / 256.0f;
float b = (float)((uid / 65536) % 256) / 256.0f;
return new Color(r, g, b);
}
}
// The above code snippet will generate a unique color for each UID by using the mod operator to map the UID to a value between 0 and 1 for each of the R, G, and B channels.
// Note: The above code snippet can generate color using the mod operator to map the UID to a value between 0 and 1 for each of the R, G, and B channels, but the color generated can be very similar if the UID numbers are close. You can try different approach as well.
// chatGPT
// One way to generate unique colors for integer UID numbers in C# is to use a hashing function to convert the UID number to a color value. For example, you could use the HashAlgorithm.ComputeHash method to generate a hash of the UID number, and then use the resulting byte array to create a color.
// Here's an example of how you could create a unique color for an integer UID using the SHA256 hashing algorithm:
using System;
using System.Drawing;
using System.Security.Cryptography;
class Example
{
public static Color GetColorForUid(int uid)
{
byte[] hash;
using (var sha = new SHA256Managed())
{
var uidBytes = BitConverter.GetBytes(uid);
hash = sha.ComputeHash(uidBytes);
}
return Color.FromArgb(hash[0], hash[1], hash[2]);
}
}
using UnityEngine;
using System.Security.Cryptography;
class Example
{
public static Color GetColorForUid(int uid)
{
byte[] hash;
using (var sha = new SHA256Managed())
{
var uidBytes = BitConverter.GetBytes(uid);
hash = sha.ComputeHash(uidBytes);
}
return new Color32(hash[0], hash[1], hash[2], 255);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment