Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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.

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

"Source file could not be found" error after editor script creates and deletes a cs file 3 Answers

UnityEditor - Drawing on a Texture 1 Answer

How can I save the Bild from a Camera, which not main camera is. 1 Answer

Get RenderTexture 1 Answer

android app: load a local image into texture by WWW class 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges