Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Rendering;
- using System.Collections;
- [ImageEffectAllowedInSceneView]
- [ExecuteInEditMode, RequireComponent(typeof(Camera))]
- public class ScreenTexture : MonoBehaviour
- {
- public string textureSemanticName = "_GlobalScreenTexture";
- #if UNITY_EDITOR
- public bool reset;
- #endif
- private RenderTexture screenRenderTexture;
- private CommandBuffer commandBuffer;
- private Camera cameraComponent;
- void OnEnable()
- {
- cameraComponent = GetComponent<Camera>();
- SetupCommandBuffer();
- }
- void OnDisable()
- {
- cameraComponent.RemoveCommandBuffer(CameraEvent.BeforeForwardAlpha, commandBuffer);
- #if UNITY_EDITOR
- if (UnityEditor.SceneView.currentDrawingSceneView != null && UnityEditor.SceneView.currentDrawingSceneView.camera != null)
- {
- UnityEditor.SceneView.currentDrawingSceneView.camera.RemoveCommandBuffer(CameraEvent.BeforeForwardAlpha, commandBuffer);
- }
- #endif
- ReleaseCommandBuffer();
- }
- void SetupCommandBuffer()
- {
- commandBuffer = new CommandBuffer();
- cameraComponent.AddCommandBuffer(CameraEvent.BeforeForwardAlpha, commandBuffer);
- //old version, fine for getting screen texture but doesn't preserve opaque alpha
- //commandBuffer.SetGlobalTexture(textureSemanticName, BuiltinRenderTextureType.CurrentActive);
- // commandBuffer.SetGlobalTexture("_GlobalStencil", BuiltinRenderTextureType.CurrentActive);
- // cameraComponent.AddCommandBuffer(CameraEvent., commandBuffer);
- // copy screen into temporary RT - this stops transparent effects interfering with the alpha buffer
- var screenCopyID = Shader.PropertyToID("_GrabTexture");
- commandBuffer.GetTemporaryRT(screenCopyID, Screen.width, Screen.height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, QualitySettings.antiAliasing > 0 ? QualitySettings.antiAliasing : 1);//-1 gets full screen size RTs | -2 get half screen | -4 screen / 4
- commandBuffer.Blit(BuiltinRenderTextureType.CurrentActive, screenCopyID);
- commandBuffer.SetGlobalTexture(textureSemanticName, screenCopyID);
- commandBuffer.ReleaseTemporaryRT(screenCopyID);
- //make the effect work with editor mode
- #if UNITY_EDITOR
- if (UnityEditor.SceneView.currentDrawingSceneView != null && UnityEditor.SceneView.currentDrawingSceneView.camera != null)
- {
- UnityEditor.SceneView.currentDrawingSceneView.camera.AddCommandBuffer(CameraEvent.BeforeForwardAlpha, commandBuffer);
- }
- #endif
- }
- void Update()
- {
- #if UNITY_EDITOR
- if (reset)
- {
- OnDisable();
- OnEnable();
- reset = false;
- }
- #endif
- }
- void ReleaseCommandBuffer()
- {
- commandBuffer.Clear();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement