- Home /
Hardcrash when using GetPixels
I have some pretty simple code- I get the pixels of a texture and then check to see how many of those pixels are clear. Here's the issue: It hard freezes Unity whenever I run it.
Two Q's: 1- Any idea why? The portion that freezes is the "checkTexture()" function 2- Is there a smarter way to be checking how many pixels are x color?
UPDATE- Its definitely the loop that's crashing this. But why?
using UnityEngine;
using System.Collections;
public class scratchoffManager : MonoBehaviour {
public GameObject front;
public GameObject back;
private Texture2D texture;
private Color[] pixelHitBlock = new Color[400];
private gameManager manager;
private int curTexSize;
private Color[] currentTex;
private int clearCounter;
void Start () {
manager = GameObject.Find ("gameManager").GetComponent<gameManager>();
for(int i = 0; i < pixelHitBlock.Length; i++){
pixelHitBlock[i] = new Color(0f,0f,0f,0f);
}
}
public void setTexture(Texture2D newTex){
back.renderer.material.mainTexture = newTex; //setTexture
Debug.Log("Set back tex?");
texture = Instantiate(front.renderer.material.mainTexture) as Texture2D; //clone the material
front.renderer.material.mainTexture = texture; //set the material equal to the clone
curTexSize = texture.height * texture.width;
currentTex = new Color[curTexSize];
StartCoroutine("checkTimer");
}
public void adjustTexture(Vector2 texCo){ //always come in a s0,0
int x = Mathf.FloorToInt(texCo.x * texture.width);
int y = Mathf.FloorToInt(texCo.y * texture.height);
Debug.Log("pixel hit at" + x + "," + y);
texture.SetPixels(x,y,20,20,pixelHitBlock);
texture.Apply();
}
private void checkTexture(){
Debug.Log("Checking the texture");
currentTex = texture.GetPixels(0,0,texture.width,texture.height);
Debug.Log("Checking the texture 2");
for(int i = 0; i < currentTex.Length; i++){
if(currentTex[i] == Color.clear){
clearCounter++;
Debug.Log("Checking the texture" + i);
}
Debug.Log("Clear counter:" + clearCounter);
clearCounter = 0;
}
}
IEnumerator checkTimer(){
yield return new WaitForSeconds(1.5f);
checkTexture();
StartCoroutine("checkTimer");
}
}
Answer by ArkaneX · Nov 08, 2013 at 10:32 AM
The freeze is caused by Debug.Log
statements. Even if your texture is relatively small, let's say 128x128, printing once for each pixel can easily take over 20 seconds.
Give this man a medal- If I was running the function once, we'd be fine. But because it was on a Corountine loop, this was creating an infinity backup of work. Removed the debug and everything is peachy!
Thanks! I was stuck on this too, was going to try to find the inner workings of getpixels! This will save me some major time debugging.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121441im_/https://answers.unity.com/themes/thub/images/avi.jpg)