80 lines
2.7 KiB
TypeScript
80 lines
2.7 KiB
TypeScript
import { _decorator, Component, js, JsonAsset, Node, resources, TypeScript } from 'cc';
|
|
import { SingletonBase } from '../SingletonBase';
|
|
import { setClassName } from '../../data/ConfigData';
|
|
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('DataMgr')
|
|
export class DataMgr extends SingletonBase<DataMgr> {
|
|
|
|
protected start(): void {
|
|
setClassName()
|
|
this.initAllConfig()
|
|
}
|
|
|
|
datas: Map<string, Array<any>> = new Map();
|
|
|
|
|
|
createInstance(className: string): any {
|
|
const Constructor = (window as any).ConfigData[className];
|
|
|
|
if (typeof Constructor === 'function') {
|
|
return new Constructor();
|
|
} else {
|
|
console.error(`Class ${className} is not a constructor`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
|
|
initAllConfig() {
|
|
resources.loadDir(`data`, null, null, (err, assets) => {
|
|
for (let i = 0; i < assets.length; i++) {
|
|
let jsonAsset = assets[i] as JsonAsset
|
|
let className = jsonAsset.name
|
|
let array = new Array<any>()
|
|
// this.datas.set((window as any)[className].name, array)
|
|
console.log("是否有类", (window as any).ConfigData, className, (window as any).ConfigData[className])
|
|
this.datas.set(js.getClassName((window as any).ConfigData[className]), array)
|
|
|
|
console.log("设置data", className, js.getClassName((window as any).ConfigData[className]))
|
|
|
|
for (let j = 0; j < jsonAsset.json.length; j++) {
|
|
let myClassInstance = new (window as any).ConfigData[className]();
|
|
let targetData: Record<string, any> = jsonAsset.json[j]
|
|
this.initDataItem(myClassInstance, targetData)
|
|
array.push(myClassInstance)
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
public GetDataById<T>(dataClass: new () => T, id: number): T {
|
|
let name = js.getClassName(dataClass)
|
|
console.log("GetDataById", name)
|
|
let datas = this.datas.get(name) as Array<T>
|
|
for (let i = 0; i < datas.length; i++) {
|
|
if (datas[i].id == id) {
|
|
return datas[i]
|
|
}
|
|
}
|
|
}
|
|
|
|
initDataItem(obj, record: Record<string, any>) {
|
|
for (const key in record) {
|
|
if (record.hasOwnProperty(key) && obj.hasOwnProperty(key)) {
|
|
obj[key] = record[key];
|
|
}
|
|
}
|
|
}
|
|
|
|
public GetDatas<T>(dataClass: new () => T): Array<T> {
|
|
let name = js.getClassName(dataClass)
|
|
console.log(this.datas.get(name))
|
|
console.log(dataClass)
|
|
console.log(name)
|
|
console.log(this.datas)
|
|
return this.datas.get(name) as Array<T>
|
|
}
|
|
|
|
} |