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 *= 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 == 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”);*
* }*
}

is "Checking the texture 2" gets printed.

1 Answer

1

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.