Editing Texture during Run time causing Unity Editor to Crash

So I am trying to make a uv map editor script for creating randomly generated characters in my game. I decided to try a prototype brute force implementation when doing this as shown in the code below. It basically grabs the main texture of the material of the object then it attempts to iterate pixel by pixel through the texture and checks for the pixel if its not black. If its not black it will change the pixel color to the given one. I am not sure what is about this causing the editor to stall and not respond when I push play. It could be that I am comparing floats a large its definitely caused by the changeColor method amount of times. I noticed no changes in CPU or RAM usage by unity.

If anyone would have any suggestions or a possible better implementation I would appreciate it.

using UnityEngine;
using System.Collections;

public class UVTextureEditor : MonoBehaviour {
	public Texture2D uvMap;
	public Color changecolor;

	// Use this for initialization
	void Start () {
		uvMap = GetComponent<MeshRenderer>().material.GetTexture("_MainTex") as Texture2D;
		Debug.Log(uvMap.width);
		Debug.Log (uvMap.height);
		this.changeColor();
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	public void changeColor(){
		for(int i = 0; i<this.uvMap.width/2;i++){
			for(int j =0; j<this.uvMap.height/2;j++){
				Color comp = uvMap.GetPixel(i,j);
				if(comp.r != Color.black.r && comp.g != Color.black.g && comp.b !=Color.black.b){
					uvMap.SetPixel(i,j,this.changecolor);
				}
			}
		}
	}

}

Got it, so the first thing I did was I Changed Texture properties to ReadEnabled and Format to Automatic Truecolor. Then I’ve modified your code a bit:

    public Texture2D uvMap;
    public Color changecolor;

    private void Start()
    {
        uvMap = (Texture2D)GetComponent<Renderer>().material.mainTexture;

        Debug.Log(uvMap.width);
        Debug.Log(uvMap.height);

        this.changeColor();
    }

    public void changeColor()
    {
        Color[] Pixels = uvMap.GetPixels(); // Get the whole Color Array (More Efficient)

        for (int x = 0; x < this.uvMap.width / 2; x++)
        {
            for (int y = 0; y < this.uvMap.height / 2; y++)
            {
                Color CurrPix = Pixels[x + y * uvMap.width];

                if (CurrPix.r != 0 && CurrPix.g != 0 && CurrPix.b != 0)
                    Pixels[x + y * uvMap.width] = this.changecolor;
            }
        }
        uvMap.SetPixels(Pixels);
        uvMap.Apply();
    }

Not sure why it crashes your Unity as well as mine but this will do it :slight_smile:
Also note that your code only colors just 1 / 4 (25%) of your Image.