编辑器实例化Prefab和运行时是不太一样的,在编辑器里创建Prefab实例是要添加上PrefabInstance这个类的实例的,目前还没有公开编辑器中创建Prefab实例的方法(编辑器专用的方法),所以需要手动添加一下。
import { _decorator, Component, Node, CCBoolean, Prefab, instantiate } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('TestPrefab')
export class TestPrefab extends Component {
// [1]
// dummy = '';
// [2]
// @property
// serializableDummy = 0;
@property({type: Prefab})
public prefab: Prefab = null;
@property()
private _build: boolean = false;
@property(CCBoolean)
set build(v: boolean) {
if (v) {
v = false;
this.buildRoad();
}
this._build = v;
}
get build() {
return this._build;
}
private createPrefabInstance(node: Node) {
// @ts-ignore
const prefabInfo = node._prefab;
if (prefabInfo) {
const prefabInstance = new Prefab._utils.PrefabInstance();
prefabInstance.fileId = node.uuid;
prefabInfo.instance = prefabInstance;
}
}
private buildRoad() {
this.node.removeAllChildren();
const nd1 = instantiate(this.prefab);
nd1.name = 'Node1';
this.createPrefabInstance(nd1);
this.node.addChild(nd1);
nd1.setPosition(0, 0, 0);
const nd2 = instantiate(this.prefab);
nd2.name = 'Node2';
this.createPrefabInstance(nd2);
this.node.addChild(nd2);
nd2.setPosition(0, 0, -10);
}
}