[Unity] I tried to draw to Texture. Part1

This time, I tried to directly draw to a texture attached a game object.

This program is very simple. To test drawing to a texture, it’s drawing yellow color at the position where the game object is locating on the red texture which is attached on a field’s game object.

[To realize this function]

There are 2 game objects and 2 C# programs for this test.

Test_Draw’ is a program for drawing, this program is attached to the red game object which is drawn.
Another program is ‘Test_Move’, this program is for moving yellow game object and send that position of the game object to ‘Test_Draw’ program.

Here, I’m just putting the source of ‘Test_Draw’ which has main function of drawing test.
(‘Test_Move’ is just moving and sending position simply calling ‘Paint_Line’.)


public class Test_Draw_01 : MonoBehaviour {

    private Texture2D drawTexture ;
    private Color[] buffer;

    // Texture size (pixel) and Object size (pixel)
    private const int C_TEXTURE_Z = 500;
    private const int C_OBJECT_X = 50;
    private const int C_OBJECT_Z = 50;

    public void Paint_Line (int point_X, int point_Z) {

        // Copy current pixels of texture to buffer
        Texture2D mainTexture = 
           (Texture2D) GetComponent<Renderer> ().material.mainTexture;
        Color[] pixels = mainTexture.GetPixels();
        buffer = new Color[pixels.Length];
        pixels.CopyTo (buffer, 0);

        // Change pixel color of drawing area
        for(int x = point_X - (C_OBJECT_X/2); 
                 x < point_X + (C_OBJECT_X/2); x++){
            for(int y = point_Z - (C_OBJECT_Z/2); 
                     y < point_Z + (C_OBJECT_Z/2); y++){
                buffer.SetValue (Color.yellow, x + C_TEXTURE_Z * y);

        // Update pixels of texture with changed pixels
        drawTexture = new Texture2D (mainTexture.width, 
              mainTexture.height, TextureFormat.RGBA32, false);
        drawTexture.filterMode = FilterMode.Point;
        drawTexture.SetPixels (buffer);
        GetComponent<Renderer> ().material.mainTexture = drawTexture;


[Explanation of the source]
This logic has following process.

  1. Get the color information of each dot of original texture, and copy those to ‘buffer’ variable.
  2. Directly change the color information on the ‘buffer’ as the same size area of the game object at the position of the game object.
    (If you change the logic of this point, you can draw anything.)
  3. Finally change the color of the texture following the updated color information of the ‘buffer’.

By changing this Step2 which is changing the color information directly on the ‘buffer’, and by calling the method with position information, you can draw anything on a texture.


[Next: I tried to draw to Texture. Part2]


[Original Japanese Site: http://blog.lab7.biz/archives/2924409.html ]


Leave a Reply

Your email address will not be published. Required fields are marked *