简体   繁体   中英

Getting current RGB color of Image

I want to change the Alpha color of image(script) component of GameObject .

But saving the RGB values of the object.

I tried the next code:

        targetObject.GetComponent<Image>().color = new Color32(
            (byte)targetObject.GetComponent<Image>().color.r,
            (byte)targetObject.GetComponent<Image>().color.g,
            (byte)targetObject.GetComponent<Image>().color.b, 
            toAlpha);

But (byte)targetObject.GetComponent<Image>().color.r returns 0 what so ever.

Any ideas?

The struct Color uses channel values in the range [0,1]. So, white is (1,1,1,1) and black (0,0,0,0). The color propriety returns a Color struct, not a Color32 .

When you cast float to byte , the result will be 1 if the channel is at 1, or 0 if is less than 1. Since you're using these values in a Color32 struct (which uses an int per channel in the range [0,255]), if the starting color is full white, you'll have an almost black of (1,1,1,1), if any channel isn't full on (ie <255 using ints), the channel will be full off.

Just change new Color32 to new Color and remove the (byte) cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM