using System;
using System.Runtime.InteropServices;
using UnityEngine;
publicclass TransparentWindow : MonoBehaviour
{
[SerializeField]
private Material m_Material;
privatestruct MARGINS
{
publicint cxLeftWidth;
publicint cxRightWidth;
publicint cyTopHeight;
publicint cyBottomHeight;
}
// Define function signatures to import from Windows APIs
[DllImport("user32.dll")]
privatestaticextern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
privatestaticexternintSetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
[DllImport("Dwmapi.dll")]
privatestaticexternuintDwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS margins);
// Definitions of window stylesconstint GWL_STYLE = -16;
constuint WS_POPUP = 0x80000000;
constuint WS_VISIBLE = 0x10000000;
void Start()
{
#if !UNITY_EDITORvar margins = new MARGINS() { cxLeftWidth = -1 };
// Get a handle to the windowvar hwnd = GetActiveWindow();
// Set properties of the window// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591%28v=vs.85%29.aspx
SetWindowLong(hwnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
// Extend the window into the client area//See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa969512%28v=vs.85%29.aspx
DwmExtendFrameIntoClientArea(hwnd, ref margins);
#endif
}
// Pass the output of the camera to the custom material// for chroma replacementvoid OnRenderImage(RenderTexture from, RenderTexture to)
{
Graphics.Blit(from, to, m_Material);
}
}
新建一个材质,选择我们刚刚写好的Shader,将TransparentWindow挂载到摄像机上,摄像机的Clear Flags选择Solid Color,Background选择和材质的Transparent Color Key相同的颜色(建议选择与模型边缘颜色相近的颜色,不然会出现较明显的毛边),将材质拖拽给TransparentWindow的Material变量。