我把blocks有关的代码贴一下 里面有成功赋值的,现在我是把赋值的动作都放里面,这样就没有问题
public blocks: BlockData[][] = [];
loadMap(): void{
resources.load(MAP_RES_PATH + 'map' + myGame.level, TextAsset, (err, data: TextAsset)=>{
if (err) {
console.error(err);
return ;
}
const originPos = this.node.getComponent(UITransform).getBoundingBox();
const text = data.text;
const textWithLines = text.replace(/[\r\n]+/g, '');
let index = 0;
//基地方块信息
const baseBlock = instantiate(this.basePrefab);
baseBlock.parent = this.blockBehind;
const parentNodeBox = this.blockBehind.getComponent(UITransform).getBoundingBox();
// baseBlock.setPosition((parentNodeBox.x + parentNodeBox.xMax) / 2, parentNodeBox.y + BASE_SIZE.y / 2);
baseBlock.setPosition(0, -(MAP_SIZE.height * BLOCK_SIZE.height) / 2 + BASE_SIZE.height / 2);
for (let i=0; i<MAP_SIZE.height; i++) {
this.blocks[i] = [];
}
for (let i=0; i<MAP_SIZE.height; i++) {
this.blocks[i].length = MAP_SIZE.width;
for(let j=0; j<MAP_SIZE.width; j++) {
const blockType = Number(textWithLines[index++]);
// 预留基地位置
if (BASE_POS.some(item => item.x === j && item.y === i)) {
this.blocks[j][i] = {type: BlockType.Base, block: baseBlock};
continue ;
}
let node: Node = null;
switch (blockType) {
case BlockType.None:
break;
case BlockType.Forest:
node = instantiate(this.forestPrefab);
break;
case BlockType.Ice:
node = instantiate(this.icePrefab);
break;
case BlockType.Wall:
node = instantiate(this.wallHalfPrefab);
break;
case BlockType.Water:
node = instantiate(this.waterPrefab);
break;
case BlockType.Swall:
node = instantiate(this.swallPrefab);
break;
default:
break;
}
if (node) {
node.parent = blockType==BlockType.Forest ? this.blockFront : this.blockBehind;
node.setPosition(originPos.x + BLOCK_SIZE.width / 2 + BLOCK_SIZE.width * j, originPos.y + BLOCK_SIZE.height * MAP_SIZE.height - BLOCK_SIZE.height / 2 - BLOCK_SIZE.height * i);
}
if (j==11 && i==10) {
console.log('地图正在初始化' + node);
}
this.blocks[j][i] = {type: blockType, block: node}
// console.log(this.blocks[j][i]);
}
}
console.log('地图初始化完成' );
// for (let i=0; i<12; i++) {
// for (let j=0; j<12; j++) {
// console.log("坐标 " + i + "|" + j + ':' + this.blocks[i][j])
// }
// }
})
// this.blocks[0][0] = null;
// this.genBaseBlock();
}