Unity制作自适应透明背景(PC端)
Posted 布纸刀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity制作自适应透明背景(PC端)相关的知识,希望对你有一定的参考价值。
实现步骤:
1.设置MainCamera
2.添加C#脚本
一、设置MainCamera里的Camera组件,以下图为例子
关键点在于 :
MainCamera->Camera->Clear Flags:Solid Color
MainCamera->Camera->Background:black
二、新建C#脚本,编写代码如下(HyalineBackground.cs)
using UnityEngine;
using System;
using System.Runtime.InteropServices;
//MainCamera->Camera->Clear Flags:Solid Color
//MainCamera->Camera->Background:black
public class HyalineBackground : MonoBehaviour
{
public string strProduct;//项目名称
private int currentX;
private int currentY;
#region Win函数常量
private struct MARGINS
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
[DllImport("user32.dll")]
static extern int SetLayeredWindowAttributes(IntPtr hwnd, int crKey, int bAlpha, int dwFlags);
[DllImport("Dwmapi.dll")]
static extern uint DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS margins);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
//private const int WS_POPUP = 0x800000;
private const int GWL_EXSTYLE = -20;
private const int GWL_STYLE = -16;
private const int WS_EX_LAYERED = 0x00080000;
private const int WS_BORDER = 0x00800000;
private const int WS_CAPTION = 0x00C00000;
private const int SWP_SHOWWINDOW = 0x0040;
private const int LWA_COLORKEY = 0x00000001;
private const int LWA_ALPHA = 0x00000002;
private const int WS_EX_TRANSPARENT = 0x20;
#endregion
IntPtr hwnd;
void Awake()
{
#if UNITY_EDITOR
print("unity内运行程序");
#else
hwnd = FindWindow(null, strProduct);
int intExTemp = GetWindowLong(hwnd, GWL_EXSTYLE);
SetWindowLong(hwnd, GWL_EXSTYLE, intExTemp | WS_EX_TRANSPARENT | WS_EX_LAYERED);
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_BORDER & ~WS_CAPTION);
currentX = 0;
currentY = 0;
SetWindowPos(hwnd, -1, currentX, currentY, Screen.currentResolution.width, Screen.currentResolution.height, SWP_SHOWWINDOW);
var margins = new MARGINS() { cxLeftWidth = -1 };
DwmExtendFrameIntoClientArea(hwnd, ref margins);
#endif
}
}
在Hierarchy视图新建空物体,添加上面建立的脚本组件即可
三、注意代码设置效果无法体现在编译器模式,将代码打包查看效果
注意Player Setting->Resolution and Presentation->Standalone Player Options->Use DXGI Filp Model Swapchain for D3D1为false
此文参考过多篇博客,可以说取其精华,实验过许多次
最后,如若项目有任何问题,欢迎批评指正或讨论。
以上是关于Unity制作自适应透明背景(PC端)的主要内容,如果未能解决你的问题,请参考以下文章