slow work script

hello everyone, so, i did simple script that changes color in texture like by pixel, it works, but very slow, how can i do it better? also no, i cant just paint it white and use button component, my originals were vector graphic and i did them a bit… bad
heres script

public class buttonColoring : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public Image button;
    public void textureColoringTech(Color color)
    {
        Texture2D texture = (Texture2D)button.mainTexture;
        texture.filterMode = FilterMode.Point;
        texture.wrapMode = TextureWrapMode.Clamp;
        for(int y = 0; y < texture.height; y++)
        {
            for(int x = 0; x < texture.width; x++)
            {
                if (texture.GetPixel(x, y) != Color.clear)
                {
                    texture.SetPixel(x, y, color);
                }
            }
        }
        texture.Apply();
    }
    public void OnPointerEnter(PointerEventData eventData)
    {
        button.color = Color.yellow;
        textureColoringTech(Color.yellow);

    }
    public void OnPointerExit(PointerEventData eventData)
    {
        button.color = Color.black;
        textureColoringTech(Color.black);
    }
}

Calculate the full texture and then use .SetPixels (or faster .SetPixels32 to use shorts)

If you want to improve heavy code the calculations you could use the job system and/or burst

1 Like

Or just change the color property of the material! :wink:

1 Like