I am trying to get texture2d from a material, which I play a movie on it by using a plug-in. I create a texture2D and assigned materials.mainTexture component to it. I can draw that texture screen using GUI.DrawTexture but when I try to Encode it to PNG file or when I read colors using GetPixels I got (0.804,0.804,0.804,0.804).
Do you have an idea about this issue? I found out some problems related to textures appearing grey when texture data is lost but I couldn’t solve my problem.
I don’t understand that why I can draw texture correctly on screen but when I try to retrieve its content it is grey.
Is it because I convert Texture to Texture2D? I do this because I can’t read pixels from Texture.
void Update () {
if (_mat == null) return;
tex = _mat.mainTexture as Texture2D;
if (tex == null) return;
for (int i = 0; i < 50; i++)
{
Debug.Log(tex.GetPixel(100, 100 + i)); // Prints (RGBA(0.804, 0.804, 0.804, 0.804))
}
count++;
}
void OnGUI() {
GUI.DrawTexture(new Rect(0, 0, 200, 200), tex); // Draws texture correctly so its content is not grey
}
It seems not to be possible to directly convert from Texture to Texture2D.
You can solve the problem by first converting the Texture into RenderTexture using Graphics.Blit() and then save it as Texture2D.
Now you can call GetPixel() or encode it as PNG or JPG and it works.
I’ve found a shorter way, so hopefully this is useful for someone who stumble the same issue, apparently its because Graphics.CopyTexture uses GPU, and GetPixels uses CPU, and this is where the synchronization issues are happening. a way to work around that is to set the RenderTexture active, like code below: