- Home /
How do I create a texture dynamically in Unity?
For example I want to create a 2 x 2 texture.
The upper left pixel would be White.
The upper right pixel would be Black.
The lower left pixel would be 50% transparent Black.
The lower right pixel would be 100% transparent.
Thanks,
Sammual
Answer by Jaap Kreijkamp · Jan 09, 2010 at 02:55 AM
function Start () {
// Create a new 2x2 texture ARGB32 (32 bit with alpha) and no mipmaps
var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false);
// set the pixel values
texture.SetPixel(0, 0, Color(1.0, 1.0, 1.0, 0.5));
texture.SetPixel(1, 0, Color.clear);
texture.SetPixel(0, 1, Color.white);
texture.SetPixel(1, 1, Color.black);
// Apply all SetPixel calls
texture.Apply();
// connect texture to material of GameObject this script is attached to
renderer.material.mainTexture = texture;
}
Other then changing texture.SetPixel(0, 0, Color(1.0, 1.0, 1.0, 0.5)); to texture.SetPixel(0, 0, Color(0, 0, 0, 0.5)); that was exactly what I needed.
Thank you!
@Jaap $$anonymous$$reijkamp, Hi I have a question related to this topic: http://answers.unity3d.com/questions/922309/applying-contrast-makes-the-image-black.html
Answer by Meltdown · Jul 02, 2015 at 04:55 AM
C# version for all the cool coders out there :)
void Start()
{
// Create a new 2x2 texture ARGB32 (32 bit with alpha) and no mipmaps
var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false);
// set the pixel values
texture.SetPixel(0, 0, new Color(1.0f, 1.0f, 1.0f, 0.5f));
texture.SetPixel(1, 0, Color.clear);
texture.SetPixel(0, 1, Color.white);
texture.SetPixel(1, 1, Color.black);
// Apply all SetPixel calls
texture.Apply();
// connect texture to material of GameObject this script is attached to
GetComponent<Renderer>().material.mainTexture = texture;
}
How can we do it if we have a camera frame and we want to use it as a texture? How can we convert the Image to texture?
How could I make texture.SetPixel() use ARGB data from an existing texture (e.g. making (24,0) on the new texture being the same color and alpha as (0,0) on an existing texture)?
It has been some time since you posted this, thanks. But I can't get it to work. It shows an error about namespace. Any ideas?
Your answer
Follow this Question
Related Questions
Same material, different meshes, different tiling 2 Answers
How do I animate procedural textures? 4 Answers
Are extremely high load times for Procedural materials normal? 0 Answers
Can't find a way to simplify this code... any help appreciated... 0 Answers
Logarithmic Spiral Code Assistance 0 Answers