Help with SetPixels32
Hi everybody,
This is my first time using SetPixels32 and I'm running into an error that I can't understand. Basically right now what I want to do is change a square of "brushSize" length to red. This is my code:
public class PaintingUVs : MonoBehaviour {
[SerializeField]
private int brushSize;
private Color32[] pixelColorArray; // stores the pixel colors we'd like to paint
void Start()
{
pixelColorArray = new Color32[brushSize * brushSize];
}
// Use this for initialization
void OnGUI () {
Event evt = Event.current;
if (evt.isMouse && Input.GetMouseButton(0))
{
// Send a ray to collide with the plane
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
// Find the u,v coordinate of the Texture
Vector2 uv;
uv.x = (hit.point.x - hit.collider.bounds.min.x) / hit.collider.bounds.size.x;
uv.y = (hit.point.y - hit.collider.bounds.min.y) / hit.collider.bounds.size.y;
// Get material
Texture2D tex = (Texture2D)hit.transform.gameObject.GetComponent<Renderer>().material.mainTexture;
if (tex != null)
{
// create a color array
for(int i =0; i < pixelColorArray.Length; i ++)
{
pixelColorArray[i] = Color.red;
}
Debug.Log("the pixel array is "+pixelColorArray.Length + " long. And our square is "+ (brushSize*brushSize).ToString() + " long");
tex.SetPixels32((int)(uv.x - brushSize/2), (int)(uv.y - brushSize/2), brushSize, brushSize, pixelColorArray);
tex.Apply(false);
}
}
}
} //end method
}
When trying to run I get a "SetPixels32 called with invalid number of pixels in the array" error. However the Debug.Log I use before the SetPixels method shows that the number of pixels in the array and the size of the square are the same. I've also tried setting brushSize to be the same as the texture size, but the error remains.
I think I must be misunderstanding how SetPixels32 works, in my mind, this code should allow you to draw a red square in the texture with a single click. Anyone knows why this error is appearing?
Thanks in advance.
Your answer
Follow this Question
Related Questions
GetPixel returning #FFFFFF (works properly in Player, breaks on Android) 1 Answer
Pick Color From Image - Unity UI 0 Answers
texture.setpixel is making a blend of colors instead of solid colors (help) (examples provided) 0 Answers
How would I go about color correcting a Raw Image? 0 Answers
Get pixelvalues from video clip 0 Answers