Unity WebGL发布及Ubuntu Apache服务器部署
Unity 中WebGL的设置
- 使用压缩格式:Project Settings->Player->Publishing Settings,将Compression Format设置为Gzip,Decompression Fallback设置为true
- 发布:Build Settings->Build,我是发布到新建的html文件夹
Ubuntu Apache web服务器搭建
- 安装 apache(Ubuntu20.04)
sudo apt-get install apache2
-
设置web资源,将之前发布的html文件夹拷贝到/var/www/html
-
添加配置文件,html/Build新建以下.htaccess文件【Unity文档】
# This configuration file should be uploaded to the server as "<Application Folder>/Build/.htaccess"
# NOTE: "mod_mime" Apache module must be enabled for this configuration to work.
<IfModule mod_mime.c>
# The following lines are required for builds without decompression fallback, compressed with gzip
RemoveType .gz
AddEncoding gzip .gz
AddType application/octet-stream .data.gz
AddType application/wasm .wasm.gz
AddType application/javascript .js.gz
AddType application/octet-stream .symbols.json.gz
# The following lines are required for builds without decompression fallback, compressed with Brotli
RemoveType .br
RemoveLanguage .br
AddEncoding br .br
AddType application/octet-stream .data.br
AddType application/wasm .wasm.br
AddType application/javascript .js.br
AddType application/octet-stream .symbols.json.br
# The following line improves loading performance for uncompressed builds
AddType application/wasm .wasm
# Uncomment the following line to improve loading performance for gzip-compressed builds with decompression fallback
# AddEncoding gzip .unityweb
# Uncomment the following line to improve loading performance for brotli-compressed builds with decompression fallback
# AddEncoding br .unityweb
</IfModule>
- 重启服务器
/etc/init.d/apache2 restart
- 查看网页
输入以下命令查看服务器IP(需要先安装net-tools)
ifconfig
在其他同一局域网的电脑上打开一个支持webGL的浏览器,输入之前查到的IP地址即可查看发布的网页界面
网页修改
打开html/index.html文件进行接下来的修改
- 添加按钮(主要是为了调试html与unity交互正常与否)
在body中加入以下代码
<button style="margin: 20px; padding: 15px" onclick="回调函数名(形参)">按钮显示的文本</button>
下图是我放置的位置
- 声明和赋值实例【十分重要,js调用的关键】
在script中添加以下代码
var myGameInstance=null;
//其他。。。。。。。。
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
myGameInstance=unityInstance;//注意加入这一句
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
}).catch((message) => {
alert(message);
});
};
- js调用Unity函数
在script中自定义函数
function update(jointIndex,qx,qy,qz,qw)
{
//最近发现只允许调用至多一个形参的函数
myGameInstance.SendMessage('GameObject名称','公共函数名',形参)
}
附一:Ubuntu 文件操作常用命令
- 复制文件夹
cp A B -r
- 删除文件
rm -rf A
- 重命名文件
mv A B
附二:Apache 服务器常用操作命令
- 查看服务器状态
systemctl status apache2
- 开关重启服务器
/etc/init.d apache2 start
/etc/init.d apache2 stop
/etc/init.d apache2 restart