1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| public class SnapScreen : MonoBehaviour { [SerializeField] Camera camera;
[Header("拍摄频率(单位秒)")] [Range(0, 1)] [SerializeField] float frequency = 0.02f; private RenderTexture renderTexture; private Texture2D texture2D; private int counter = 1; private bool startSnap = false; private string folder = null; private static SnapScreen instence = null;
private void Start() { folder=Application.dataPath + "/pic"; renderTexture = new RenderTexture(1280, 720, 32); texture2D = new Texture2D(1280, 720, TextureFormat.ARGB32, false); camera.targetTexture = renderTexture; instence = this; }
private void snapCameraShort() { RenderTexture.active = renderTexture; texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); texture2D.Apply(); RenderTexture.active = null;
byte[] bytes = texture2D.EncodeToPNG(); string index = string.Format("{0:d3}", counter); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); File.WriteAllBytes($"{folder}/{index}.png", bytes); ++counter; }
private void snapAnim() { if(startSnap) { InvokeRepeating("snapCameraShort",0, frequency); } else { if (IsInvoking("snapCameraShort")) { CancelInvoke("snapCameraShort");
Debug.Log($"截取成功,位于:{instence.folder}"); Application.OpenURL($"file:///{instence.folder}"); UnityEditor.AssetDatabase.Refresh(); } } }
#if UNITY_EDITOR [UnityEditor.MenuItem("Tools/截取一张相机内容 &n")] private static void snapOnePicTool() { if (!Application.isPlaying) { Debug.LogError("需要运行才能拍摄"); return; } instence.counter = 1; instence.snapCameraShort(); Debug.Log($"截取成功,位于:{instence.folder}"); Application.OpenURL($"file:///{instence.folder}"); UnityEditor.AssetDatabase.Refresh(); }
[UnityEditor.MenuItem("Tools/录制相机动画 &m")] private static void snapAnimTool() { if (!Application.isPlaying) { Debug.LogError("需要运行才能拍摄"); return; }
instence.startSnap = !instence.startSnap; instence.counter = 1; instence.snapAnim(); } #endif }
|