Hey guys,
I’m having a bit of a strange issue with this procedure…
Below are my requirements.
In game runtime:
+Cycle a list of Substances
+For each one, get the “Main Texture” (Albedo, Diffuse)
+Convert it to a texture2D
+Convert it to a sprite
The goal is to generate material “previews” to be added on a GUI control. These need to be sprites.
Now, I have been able to do all that, but there is a single issue that is bothering me:
+The first time I run the game (either on the editor or as a build), I get black squares for all generated previews
+On the second run, I get some of the textures as I wanted
+On the third run, I get all the textures
+After that it works flawlessly 
To fix this, I’ve tried the following approach:
+Generating .png files from the substances and use those for sprite conversion (to be done on the first ever run)
+Adding timers, events and such to have the substance extraction happen over time
+Getting the conversion process to run on it’s own thread (CoRoutine)
So far, no improvement. I’ve debunked issues for performance (hardware+code), timing and I\O. And I’m starting to believe that it might be some substance processing or interpretation issue.
I’ve set the substance’s format to RAW on the inspector and I’m setting isReadable=true before extracting the texture. I’ve also tested different load behaviours (Bake and Keep Substance, Do Nothing, Build On Level Load, Build and keep cache), but the end result is more or less the same.
This is the procedure I’ve used to do the conversion:
Texture2D ConvertProceduralToText(Material target, string path)
{
ProceduralMaterial material = target as ProceduralMaterial;
material.isReadable = true;
ProceduralTexture mat = material.mainTexture as ProceduralTexture;
Color32[] pixels = mat.GetPixels32(0, 0, mat.width, mat.height);
Texture2D tempText = new Texture2D(mat.width, mat.height);
tempText.name = mat.name;
tempText.anisoLevel = mat.anisoLevel;
tempText.filterMode = mat.filterMode;
tempText.mipMapBias = mat.mipMapBias;
tempText.wrapMode = mat.wrapMode;
for (int i = 0; i < pixels.Length; i++)
{
pixels[i].a = 255;
}
tempText.SetPixels32(pixels);
tempText.Apply();
File.WriteAllBytes(path + "/" + tempText.name + ".png", tempText.EncodeToPNG());
return tempText;
}
I’m at loss with this issue, since I can’t explain why it only works after 3 runs and why do I get all-black images/.pngs on the first run.
Can anyone help? Thanks for the time and for the input!