Float to Byte for Color32

How do I take a float (0f to 1f) and convert that to a byte (not a byte array) for a Color32’s alpha channel (0-255)?

I have an function I wrote awhile back, SetAlpha, that takes a float from 0f to 1f and sets it to the alpha channel of a Color. With some new changes I’ve made, I now need to use Color32 instead of Color to set alpha. Accessing .a doesn’t work as it takes a byte, not a float (and I can’t Mathf.RoundToInt either).

I suspect this is probably pretty simple but I’ve never worked with Color32 before, and don’t know the syntax. Thank you!

(byte) (your01float * 255)


You could try this:

float randomAlphaValue = 0.43f;

color.r = (byte) ((int) (randomAlphaValue * 255) % 256)

The modulo % 256 is not strictly necessary, since only the right-most byte of the int value you pass is used. You could also omit the int casting.

I casted it to Color32 like this:

UnityEngine.Color sourceColor = new UnityEngine.Color(0.5f, 0.5f, 0.5f, 0.5f);
UnityEngine.Color32 convertedColor;
convertedColor = sourceColor;