使用unity导入粒子特效,在Laya中第一次播放会出现卡顿现象,查了下相关资料发现是特效的shader没有进行预编译导致的,根据Laya官网实现如下代码
先整体运行跑一边项目执行 getShaderData() 保存输出的文件,以后每次启动执行预编译compileShader(data)就可以避免第一播放粒子特效时候的卡顿,当然预编译时还是会卡顿的。参考链接:https://ldc2.layabox.com/doc/?nav=zh-ts-4-22-7.
public static getShaderData() {
let shaderObj = {};
let arr = new Array();
for (let i = 0; i < Laya.Shader3D.debugShaderVariantCollection.variantCount; i++) {
let shadervariant: Laya.ShaderVariant = Laya.Shader3D.debugShaderVariantCollection.getByIndex(i);
let shaderName: string = shadervariant.shader.name;
if (!shaderObj[shaderName]) shaderObj[shaderName] = [];
arr = shaderObj[shaderName];
let obj: any = {};
obj.defineNames = shadervariant.defineNames;
obj.passIndex = shadervariant.passIndex;
obj.subShaderIndex = shadervariant.subShaderIndex;
arr.push(obj);
}
console.log("ShaderData: ", shaderObj);
return shaderObj;
}
public static compileShader(data) {
let shaderData = data;
console.log(data);
for (const key in shaderData) {
const element1 = shaderData[key];
for (let i = 0; i < element1.length; i++) {
const element2 = element1[i];
Laya.Shader3D.compileShaderByDefineNames(key, element2.subShaderIndex, element2.passIndex, element2.defineNames);
}
}
}
其实上面方法可行,但是还是有些笨,要先整体运行一遍保存预编译的配置表,再在以后运行时执行。如果新加入特效材质又要重复上面的操作。后面又参考网上大神手动解析Laya导出的场景文件,自己去记录并预编译shader, 并没生效0.0 参考链接:http://ask.layabox.com/question/41865.
public static prewarmParticle(particle: any) {
if (particle instanceof Laya.ShuriKenParticle3D) {
const render: any = particle.particleRenderer;
let publicDefine = 0;
let materialDefine = [];
const spriteDefine: number = 0;
particle.particleRenderer.materials.forEach($mat => {
const matAny: any = $mat;
publicDefine = 0
materialDefine = matAny._shaderValues._defineDatas._mask;
if (matAny._shader) {
Laya.Shader3D.compileShader(matAny._shader._name, 0, 0, materialDefine);
}
});
}
if (particle._children) {
for (var i: number = 0; i < particle._children.length; i++) {
this.prewarmParticle(particle._children[i]);
}
}
}
我用的Laya版本是2.11.0,可能跟参考链接里的版本不一致导致里面api改动而失去效果,本人对shader相关还是一知半解的状态,希望有大佬指出自己手动解析编译不行的问题出在哪里…
|