Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Color a greyscale images using a gradient

Discussion in 'Scripting' started by Ardan, Jun 28, 2011.

  1. Ardan

    Ardan

    Joined:
    Oct 5, 2009
    Posts:
    68
    I'm working on a script that randomally generates a greyscale image. What i want is something similar to what is found on this page http://libnoise.sourceforge.net/tutorials/tutorial3.html ,in the middle of the page. So i want to somehow apply a premade gradient to each color value in each pixel. I have my gradient set up as a Texture2D.

    I hope you understand what i'm trying to do.

    What would be the best way to achieve this?
     
  2. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    You would have to have a gradient 1 pixel wide and 256 pixel's tall.

    get both textures into a color array:
    http://unity3d.com/support/documentation/ScriptReference/Texture2D.GetPixels.html

    read each pixel in your height map and replace it with a pixel that many bytes into the second array.
    Code (csharp):
    1.  
    2. for(var i=0; i<heightmapColors.Length; i++){
    3. heightmapColors[i]=gradientColors[heightmapColors[i].r];
    4. }
    5.  
    Apply it back to teh texture:
    http://unity3d.com/support/documentation/ScriptReference/Texture2D.SetPixels.html

    and appy your changes
    http://unity3d.com/support/documentation/ScriptReference/Texture2D.Apply.html





    Just in case you need more info.
    http://unity3d.com/support/documentation/ScriptReference/Texture2D.html
     
  3. Ardan

    Ardan

    Joined:
    Oct 5, 2009
    Posts:
    68
    Thanks, this was exactly what i was looking for. I will give it a try
     
  4. Ardan

    Ardan

    Joined:
    Oct 5, 2009
    Posts:
    68
    I'm a bit stuck now, i have done what you put in the code window, and i've tried applying and saving but all i get is a blank texture.
    Can you give me some directions on how the whole apply thing would work?

    I don't know if this is the problem, but Unity wont let me create a texture 1pixel wide (or tall) it gets resized to 256x2. I guess that is because of the "Non Power of 2" which is greyed out for me.
     
    Last edited: Jun 29, 2011
  5. Ardan

    Ardan

    Joined:
    Oct 5, 2009
    Posts:
    68
    Solved to with help from UnityAnswers, for those interested i've posted my functioning script there:
    HERE