Skip to content

Instantly share code, notes, and snippets.

@EddieCameron
Last active November 26, 2020 20:20
Show Gist options
  • Save EddieCameron/0150940a74abd658977e3b438a6593ac to your computer and use it in GitHub Desktop.
Save EddieCameron/0150940a74abd658977e3b438a6593ac to your computer and use it in GitHub Desktop.
Add to your scene to have a shader keyword enabled/disabled only for the scene view. Use for debug materials, scene visualisations
/* SceneViewShaderKeyword.cs
* © Eddie Cameron 2020
* ----------------------------
*/
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// Set a shader keyword when rendering the scene view in editor
/// adapted from https://forum.unity.com/threads/image-effect-in-scene-editor-views.102515/
/// </summary>
[ExecuteInEditMode]
public class SceneViewShaderKeyword : MonoBehaviour {
public string keyword;
public bool onInSceneView;
#if UNITY_EDITOR
Camera cam;
SceneViewShaderKeyword sceneViewInstance;
bool isSceneViewCam;
bool previousKeywordState;
private Camera GetCamera()
{
return SceneView.lastActiveSceneView?.camera;
}
// These are only called when attached to the scene view camera object
void OnPreRender() {
if ( !isSceneViewCam )
return;
previousKeywordState = Shader.IsKeywordEnabled( keyword );
if ( onInSceneView )
Shader.EnableKeyword( keyword );
else
Shader.DisableKeyword( keyword );
}
void OnPostRender() {
if ( !isSceneViewCam )
return;
if ( previousKeywordState )
Shader.EnableKeyword( keyword );
else
Shader.DisableKeyword( keyword );
}
void Update() {
if ( !isSceneViewCam ) {
// update scene view camera
if ( sceneViewInstance == null ) {
if ( cam == null )
cam = GetCamera();
if ( cam == null ) // This shouldn't happen, but it does
return;
sceneViewInstance = cam.GetComponent<SceneViewShaderKeyword>() ?? cam.gameObject.AddComponent<SceneViewShaderKeyword>();
}
sceneViewInstance.isSceneViewCam = true;
sceneViewInstance.keyword = keyword;
sceneViewInstance.onInSceneView = onInSceneView;
}
}
#endif
}
@EddieCameron
Copy link
Author

slope_debug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment