本节目标
实现无缝创建/回收 对象
laya商业级3d游戏开发
导出场景素材到Laya
进行场景的构建
新建Example04_Spawn.ts
export class Example04_Spawn extends Laya.Script {
scene:Laya.Scene3D;
}
Mian.ts
onConfigLoaded(): void {
this.example_spwan();
}
example_spwan() {
let node = new Laya.Node();
Laya.stage.addChild(node);
node.addComponent(UnityEnagine)
SceneManager.LoadSceneByName('Example_BuildLoop', this, (p_Scene3D) => {
Laya.stage.addChild(p_Scene3D);
let examlpe05_Spawn = new Example04_Spawn()
examlpe05_Spawn.scene = p_Scene3D;
node.addComponentIntance(examlpe05_Spawn);
});
}
实现Example04_Spawn
需求主干整理
无缝地图伪代码
Update()
{
//定义线段的 开始 和结束 范围 currentz ,endz
//在范围内创建物体
//回超出范围物体
}
实现: 创建物体
ExamlpeSpawn.ts
onStart() {
this.CloneGo();
}
protected CloneGo(): Laya.Sprite3D {
//原型
// var gob = this.scene.getChildByName('Resources').getChildByName('BuildItem').getChildByName('IndustrialWarehouse01') as Laya.Sprite3D
//框架封装,查找路径对象
var gob = GameObject.Find<Laya.Sprite3D>(this.scene, 'Resources/BuildItem/IndustrialWarehouse01');
var newGo = Laya.Sprite3D.instantiate(gob);
this.scene.addChildren(newGo);
newGo.active = true;
return newGo;
}
F8 F5,此时场景实例化了创建了指定的对象
//实现:在指定的范围内使用对象池创建物体
//设开始坐标为0,长度为100
currentZ = 0;
startCreateZ = 0;
length = 100;
protected endZ(): number {
return this.currentZ + this.length;
}
//区间内创建物体
Create2End() {
var p_endZ = this.endZ();
while (this.startCreateZ < p_endZ) {
let length = this.CreateItem(this.startCreateZ);
this.startCreateZ += length;
}
}
//创建物体设置坐标,返回物体长度
protected CreateItem(z: number): number {
//对象池创建Laya.Pool.getItemByCreateFun
var newGo = Laya.Pool.getItemByCreateFun('IndustrialWarehouse01', () => { return this.CloneGo(); }, this) as Laya.Sprite3D;
newGo.active = true;
this.scene.addChild(newGo);
newGo.transform.position = new Laya.Vector3(0, 0, z);;
return 18;
}
更改onstart
F5
实现:超出范围后回收
增加字段
runtimeGobs: Laya.Sprite3D[] = [];
补上对象实例表,进行回收管理
CloneGo() …
//给回收用的
this.runtimeGobs.push(newGo as Laya.Sprite3D);
//回收超出范围的且在场景内的物体
recoverLessZ() {
for (const item of this.runtimeGobs) {
//在场景内的物体?
if (item.displayedInStage) {
let height = 18;
if (item.transform.position.z + height * 0.5 < this.currentZ) {
Laya.Pool.recover(item.name, item);
item.removeSelf();
}
}
}
}
onUpdate() {
this.currentZ += 1;
//在范围内 创建物体
this.Create2End();
//回收超出范围的物体
this.recoverLessZ();
}
F5
因为使用了对象池 测试内存和sprite数值 稳定