Hello Guest

Author Topic: SOLVED: Odd results when setting a random color in code.  (Read 6091 times)

josriley

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 14
    • View Profile
SOLVED: Odd results when setting a random color in code.
« on: March 03, 2013, 01:10:59 am »
I have this code in my Start() function, and want to completely randomize clothing colors for my sprites. For some reason this line of code sets the r,g,b values of my sprite to very high numbers (4 digit numbers), based on what the inspector tells. The alpha value is set as expected.

tk2dBaseSprite sprite = GetComponent<tk2dBaseSprite>();
sprite.color =new Color(Random.Range(0,256), Random.Range(0,256),Random.Range(0,256),255);

I've also noticed that setting the values explicitly yields odd results. Setting it to (100,100,100,255) actually sets it to (40,43,112,255).
« Last Edit: March 03, 2013, 02:41:57 am by josriley »

josriley

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 14
    • View Profile
Re: Odd results when setting a random color in code.
« Reply #1 on: March 03, 2013, 01:16:45 am »
Actually, I read it wrong, its setting it (25500,25500,25500,255) if I set to (100,100,100,255). I'm guessing color is on a scale of 0-1?

josriley

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 14
    • View Profile
Re: Odd results when setting a random color in code.
« Reply #2 on: March 03, 2013, 01:20:21 am »
Looks like that's the case, in case anyone else has this problem. This code solves the issue:

sprite.color =new Color(
     (float)Random.Range(0,1000)*.001f,
     (float)Random.Range(0,1000)*.001f,
     (float)Random.Range(0,1000)*.001f,
     255);

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Odd results when setting a random color in code.
« Reply #3 on: March 03, 2013, 01:49:48 am »
Color is in the range 0 - 1, as is the alpha.
You could just do this:
sprite.color = new Color( Random.value, Random.value, Random.value, 1 );
// note the 1 in the alpha channel, not 255

josriley

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 14
    • View Profile
Re: Odd results when setting a random color in code.
« Reply #4 on: March 03, 2013, 02:41:46 am »
Yeah, noticed that too. It looks like it takes a value over 1 as 1, so it doesn't affect it negatively, but I've fixed that as well. I think I was just confused since it shows it on a 1-255 scale in the Inspector.

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: SOLVED: Odd results when setting a random color in code.
« Reply #5 on: March 03, 2013, 09:30:07 am »
That is a bit confusing. I think they've made it 0-255 to appeal to people accustomed to PS / Flash but in reality the values are 0..1, and can go above that too for HDR values.