I've noticed that one cannot really dynamically modify textures and expect them to animate with any sort of regularity. This may be an Editor specific issue. I am hoping that I can create a "paint" tool in unity but I don't seem to be able to draw reliably. I'm hoping it's just something I'm missing.
Here's my code:
using UnityEditor;
using UnityEngine;
using System.Collections;
public class TestEditor : EditorWindow {
[MenuItem("Editor/TestEditor")]
static void ShowWindow ()
{
EditorWindow.GetWindow<TestEditor> ();
}
Texture2D canvas;
Color[] colors;
bool isInitialized = false;
bool penDown =false;
int offset =0;
public TestEditor()
{
}
int count =0;
public void OnGUI()
{
this.wantsMouseMove = true;
canvas = getWhiteCanvas(canvas, (int)(position.width/2), (int)( position.height/2));
colors = canvas.GetPixels();
GUI.Box (new Rect(0,0,canvas.width, canvas.height), canvas);
Event current = Event.current;
switch(current.type)
{
case EventType.Repaint:
Debug.Log("Repaint:" +count++);
//if(penDown == true)
{
/*
int x = (int) current.mousePosition.x;
int y = (int) ((float)(canvas.height) - current.mousePosition.y);
//Debug.Log("MouseMove:" + x + ":" + y);
if (x < canvas.width && y < canvas.height)
{
colors[y * canvas.width + x] = Color.blue;
canvas.SetPixels(colors);
canvas.Apply();
}
*/
}
break;
case EventType.MouseDown:
//Debug.Log("MouseDown:" + current.mousePosition.x + ":" + current.mousePosition.y);
penDown = true;
break;
case EventType.MouseUp:
//Debug.Log("MouseUp:" + current.mousePosition.x + ":" + current.mousePosition.y);
penDown = false;
break;
}
}
public void Update()
{
// Fill the texture with Sierpinski's fractal pattern!
int y = 0;
while (y < canvas.height) {
int x = 0;
while (x < canvas.width) {
Color color = ((x+offset & y+offset) == 0)?Color.white:Color.gray;
canvas.SetPixel(x, y, color);
++x;
}
++y;
}
canvas.Apply();
offset = offset + 1 % canvas.width;
}
//-----------------------------------------------------------------------------
public Texture2D getWhiteCanvas(Texture2D current, int width, int height)
{
Texture2D canvas = current;
if (canvas == null)
{
canvas = new Texture2D(width, height, TextureFormat.ARGB32, false);
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
canvas.SetPixel(x,y,Color.white);
}
else if (canvas.width != width || canvas.height != height)
{
canvas = new Texture2D(width, height, TextureFormat.ARGB32, false);
int oldWidth = (current.width < width) ? current.width : width;
int oldHeight = (current.height < height) ? current.height : height;
for(int x = 0; x < oldWidth; x++)
for(int y = 0; y < oldHeight; y++)
canvas.SetPixel(x,y,current.GetPixel(x,y));
}
canvas.Apply();
return canvas;
}
}