• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by CaKeMeaT · Mar 15, 2018 at 07:35 PM · editor-scriptingtexture2drendertexturefile

Saving texture of selected GO (Editor Script)

I am having trouble using my Editor script to save the selected objects texture to file. Right now, it saves a small 241 pixel square from what the Scene view shows, and not the texture on the object. Does anyone have any experience with this?

TLDR/Goal; Save the texture of a selected GO's Mesh to a file.

 using UnityEngine;
 using System.Collections;
 using UnityEditor;
 using System.IO;
 
 [CustomEditor(typeof(MeshRenderer))]
 public class SaveMaterialAsAsset : Editor
 {
 
     public override void OnInspectorGUI()
     {
         if (GUILayout.Button("Save Material as File"))
         {
             DrawDefaultInspector();
 
             //Renderer renderer2 = target as Renderer; // captures view both work
             MeshRenderer renderer2 = (MeshRenderer)target; // captures view both work
 
             Material material = new Material(renderer2.sharedMaterial);
             SavePNG(material);
         }
     }
 
     void SavePNG(Material mat)
     {
         int width = mat.mainTexture.width;
         int height = mat.mainTexture.height;
 
         Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
 
         tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
         tex.Apply();
 
         // Encode texture into PNG
         byte[] bytes = tex.EncodeToPNG();
         Object.Destroy(tex);
 
         File.WriteAllBytes(Application.dataPath + "/../Assets/Materials/Saved/SavedScreen" + System.DateTime.Now.ToString("yyyymmdd") +".png", bytes);
     }
 
 }
Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CaKeMeaT · Mar 15, 2018 at 11:15 PM 0
Share

I wonder if Selection.activeTransform.gameObject.GetComponent().material or similar is needed.

avatar image Remy_Unity CaKeMeaT · Mar 16, 2018 at 12:06 PM 0
Share

@Grish_tad has part of the anser : your need to get the correct object from selection.

Also, ins$$anonymous$$d of creating a new texture, you cand directly do :

 byte[] bytes = mat.mainTexture.EncodeToPNG();

And last but not least, you can also use assetdatabase to find mat.mainTexture path, and use File.Copy to copy directly the file.

Doing this will export the texture source, while Texture2D.ReadPixel will get the compressed texture.

2 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by Bunny83 · Mar 16, 2018 at 01:09 PM

If your texture that you want to save is actually a Texture2D you can simply do:

 [CustomEditor(typeof(MeshRenderer))]
 public class SaveMaterialAsAsset : Editor
 {
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
         if (GUILayout.Button("Save Material as File"))
         {
             Renderer renderer = (Renderer)target;
             Material mat = renderer.sharedMaterial;
             Texture2D tex = (Texture2D)mat.mainTexture;
             byte[] data = tex.EncodeToPNG();
             File.WriteAllBytes(Application.dataPath + "/../Assets/Materials/Saved/SavedScreen" + System.DateTime.Now.ToString("yyyymmdd") +".png", data);
           }
       }

  

If your texture is not a Texture2D you can use CopyTexture to copy the context of the source texture into a temporary texture. To cover both cases you could replace those two lines:

     Texture2D tex = (Texture2D)mat.mainTexture;
     byte[] data = tex.EncodeToPNG();

with this:

     Texture2D tex = mat.mainTexture as Texture2D;
     byte[] data;
     if (tex == null)
     {
         Texture source = mat.mainTexture;
         if (source == null)
             return;
         tex = new Texture2D(source.width, source.height, TextureFormat.ARGB24, false);
         Graphics.CopyTexture(source, tex);
         data = tex.EncodeToPNG();
         DestroyImmediate(tex);
     }
     else
     {
         data = tex.EncodeToPNG();
     }
     File.WriteAllBytes(Application.dataPath + "/../Assets/Materials/Saved/SavedScreen" + System.DateTime.Now.ToString("yyyymmdd") +".png", data);


However keep in mind that this code will just save the texture of the material of the selected meshrenderer as it is. Your filename looks like you want to save a screenshot which this code doesn't do.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by Grish_tad · Mar 16, 2018 at 11:37 AM

Hi @CaKeMeaT , try this

 using UnityEngine;
  using System.Collections;
  using UnityEditor;
  using System.IO;
  
  [CustomEditor(typeof(MeshRenderer))]
  public class SaveMaterialAsAsset : Editor
  {
  
      public override void OnInspectorGUI()
      {
          if (GUILayout.Button("Save Material as File"))
          {
              DrawDefaultInspector();
              GameObject obj = Selection.activeGameObject;
               
              //Renderer renderer2 = target as Renderer; // captures view both work
              //MeshRenderer renderer2 = (MeshRenderer)target; // captures view both work
  
              //Material material = new Material(renderer2.sharedMaterial);
              SavePNG( obj.GetComponent<Renderer>().sharedMaterial);
          }
      }
  
      void SavePNG(Material mat)
      {
          int width = mat.mainTexture.width;
          int height = mat.mainTexture.height;
  
          Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
  tex= mat.mainTexture;
         // tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
          tex.Apply();
  
          // Encode texture into PNG
          byte[] bytes = tex.EncodeToPNG();
          Object.Destroy(tex);
  
          File.WriteAllBytes(Application.dataPath + "/../Assets/Materials/Saved/SavedScreen" + System.DateTime.Now.ToString("yyyymmdd") +".png", bytes);
      }
  
  }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Mar 16, 2018 at 12:50 PM 1
Share

While this is more correct than the original code those three lines make no sense:

 Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
 tex= mat.mainTexture;
 tex.Apply();

You create a new texture and store it in the "tex" variable. Then you replace the texture in tex with the texture from the material which makes the newly created texture unavailable anymore. Apply is also pointless since nothing has been changed on the texture.

 Object.Destroy(tex);

This line would try to destroy the actual texture from the material since that is referenced in the tex variable. So also pointless. As a sidenote "Destroy" can't be used from an editors script. You have to use DestroyImmediate at edit time.


Finally the DrawDefaultInspector has to be called outside the button.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

89 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

blending colors on a texture: shader, render texture, or other 2 Answers

how to checking If texture is in use in hierarchy 1 Answer

How can I build a RenderTexture to Texture2D hidden booth for UI elements? 1 Answer

RenderTexture not working correctly 0 Answers

Get pixels from material displaying camera feed - LiveTexture Plugin 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges