- Home /
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!
Answer by FM-Productions · May 30, 2017 at 10:37 PM
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.
You are right, I saw your answer only after I have written $$anonymous$$e. But I will leave $$anonymous$$e also here :)
Answer by bison-- · Sep 14, 2020 at 06:02 AM
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;