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

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;
}

C# version for all the cool coders out there :slight_smile:

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;
	}