简体   繁体   中英

Generating random color in Unity isn't working properly

So i have a very strange bug i think.. I have a script where i generate a random color and assign it to the player, the thing is that the color is always white but when i look to the color panel in inspector it is showing a normal random color.Another fun thing is that when i change the color in inspector in play mode it actually changes在此处输入图像描述

    float R = Random.Range(0, 226);
    float G = Random.Range(0, 226);
    float B = Random.Range(0, 226);
    ColorToBeGenerate = new Color(R, G, B);
    Player.GetComponent<SpriteRenderer>().color = ColorToBeGenerate;

Edit:

Color constructor takes float values from 0 to 1 .. not int between 0 to 255. as derHuge Mentioned

change your code as following

float R = Random.Range(0, 226/255f);
float G = Random.Range(0, 226/255f);
float B = Random.Range(0, 226/255f);
ColorToBeGenerate = new Color(R, G, B);
Player.GetComponent<SpriteRenderer>().color = ColorToBeGenerate;

The actual reason is: Color constructor takes float values from 0 to 1 .. not int between 0 to 255. So your random values between 0 and 225 (the 226 is exclusive) will be clamped to 1 so it is most likely (with a chance of 225 to 1) that the result will always be 1 or in the other case 0 . -> Color will always result in white.

So yes you either have to change it to values between 0 and 1 like in the other answer

or alternatively use Color32 with int values between 0 and 255 like

int R = Random.Range(0, 227);
int G = Random.Range(0, 227);
int B = Random.Range(0, 227);
ColorToBeGenerate = new Color32(R, G, B, 255);
Player.GetComponent<SpriteRenderer>().color = ColorToBeGenerate;

Color32 can be implicitly converted to Color and vice versa.

I had a similar bug a while ago. Using a Color32 instead of a Color fixed it for me.

public Color color; color = new Color(Random.value,Random.value, Random.value, 1.0f); alpha argument is there

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