I am trying to set up a Texture2D using either the material/texture of a GameObject or by loading a material/texture from my Resources folder, but keep getting the following error:
NullReferenceException: Object reference not set to an instance of an object
Here is the code I’ve been TRYING to use with no success:
**First attempt:**
Texture2D tex = new Texture2D(200,200);
tex = Resources.Load("imageCamera") as Texture2D;
byte[] bytes = tex.EncodeToPNG();
Destroy(tex);
File.WriteAllBytes(Application.persistentDataPath + "/SavedS2creen.png", bytes);
**Second attempt:**
Texture2D tex2 = GameObject.Find("CapturedPicture").renderer.material.GetTexture("_MainTex") as Texture2D;
byte[] bytes = tex2.EncodeToPNG();
If anyone has any idea how to help me out, I would really appreciate it.
EDIT: I know that for sure the material/texture that I’m trying to load is not null. If you look at my “second attempt”, you’ll see that I have a GameObject called CapturedPicture. That has the material in question that I want to assign to a Texture2D.