Yes, I know - this was for testing on desktop. I modified my code again, to find what’s null:
public function OnEnter()
{
var go : GameObject = Fsm.GetOwnerDefaultTarget(gameobject);
var tx2d = Texture2D(go.renderer.material.mainTexture.width,go.renderer.material.mainTexture.height,TextureFormat.RGB24, false);
Debug.Log("Test Start");
var ren : Renderer = go.renderer;
if (ren == null) Debug.Log("1 failed"); else Debug.Log("1 passed");
var mat : Material = go.renderer.material;
if (mat == null) Debug.Log("2 failed"); else Debug.Log("2 passed");
var tex : Texture = go.renderer.material.mainTexture;
if (tex == null) Debug.Log("3 failed"); else Debug.Log("3 passed");
var tex2 : Texture2D = go.renderer.material.mainTexture as Texture2D;
if (tex2 == null) Debug.Log("4 failed"); else Debug.Log("4 passed");
tx2d.SetPixels((go.renderer.material.mainTexture as Texture2D).GetPixels());
tx2d.Apply();
if (filePath != null) filePath = "/" + filePath;
File.WriteAllBytes(Application.persistentDataPath + filePath + "/" + fileName + ".png",tx2d.EncodeToPNG());
}
And the result:
This line of code produce the error var tex2 : Texture2D = go.renderer.material.mainTexture as Texture2D;
So this means, that the convertion to Texture2D does not work, because one line above var tex : Texture = go.renderer.material.mainTexture;
passes fine, without result null - so there must be a texture.
But why it won’t convert to Texture2D?
EDIT:
I also tried it via ReadPixels:
tx2d.ReadPixels(new Rect(0,0,go.renderer.material.mainTexture.width,go.renderer.material.mainTexture.height),0,0);
This brings me another error:
ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
–.–
BTW:
Is there a way to see, what the compiler changes on ‘wrong’ code, if dynamic typing is on? So I could look up, what the compiler makes with this line of code, which works great on desktop with dynamic typing tx2d.SetPixels(go.renderer.material.mainTexture.GetPixels());
and it could not be tx2d.SetPixels((go.renderer.material.mainTexture as Texture2D).GetPixels());
because if I switch the line to this, my App breaks at this line (with the ‘wrong’ syntaxline, which will be fixed via dynamic typing it works, so it would be great to see, what the compiler changes to it).