MakeShotScript.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #if(UNITY_EDITOR)
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEditor;
  6. using UnityEngine;
  7. public class MakeShotScript : MonoBehaviour {
  8. [SerializeField]
  9. public NPC npc;
  10. [SerializeField]
  11. public RenderTexture render_texture;
  12. public void button_function()
  13. {
  14. Texture2D tex2d = new Texture2D(256, 256);
  15. RenderTexture.active = render_texture;
  16. tex2d.ReadPixels(new Rect(0, 0, render_texture.width, render_texture.height), 0, 0);
  17. tex2d.Apply();
  18. SaveSprite(tex2d);
  19. }
  20. void SaveSprite(Texture2D tex)
  21. {
  22. string assetPath = "Assets/Resources/Avatar/NPC/" + npc.Name+"_2.png";
  23. Sprite sp = Sprite.Create(
  24. tex,
  25. new Rect(0, 0, tex.width, tex.height),
  26. new Vector2(0, 0),
  27. 30);
  28. sp.name = "SpriteName";
  29. //Debug.Log("Saved PPU: " + sp.pixelsPerUnit); // Saved PPU: 30
  30. // Would prefer a Unity specific way to do this but AssetDatabase.CreateAsset wasn't working.
  31. // Due to it being a .png instead of .asset?
  32. File.WriteAllBytes(Application.dataPath + "/../" + assetPath, tex.EncodeToPNG());
  33. AssetDatabase.Refresh();
  34. AssetDatabase.AddObjectToAsset(sp, assetPath);
  35. AssetDatabase.SaveAssets();
  36. sp = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Sprite)) as Sprite;
  37. //Debug.Log("Loaded PPU: " + sp.pixelsPerUnit); // Loaded PPU: 100
  38. }
  39. }
  40. #endif