解析 unity txt 数据文件方法


解析 unity txt 数据文件方法

  • txt数据样例
1
2
3
4
5
6
7
8
9
#	技能配置表	
# ID RoleClass Name Type Info
# int int string int string
# 编号 角色职业 名称 攻击类型 描述
1 1 剑术 1
2 1 剑法 1
3 1 弯刀 1
4 1 冲撞 5
5 1 烈火 1
  • 动态加载方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
cc.loader.loadResDir(url, (err, assets) => {
if (err) {
if(callback) callback(true);
return;
}
if (assets.length <= 0) {
if(callback) callback(true);
return;
}
for (let i in assets) {
if (assets[i] instanceof cc.JsonAsset) {
let as = assets[i];
this.data[as.name] = as.json;
}else if (assets[i] instanceof cc.TextAsset) {
let as = assets[i];
this.data[as.name] = game.utils.cvsToObj(as.text);
}
}
if(callback) callback(true);
});
  • 解析方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
cvsToObj(csv, columnDelimiter = '\t'){
let obj = {};
let arrTable = this.csvToArray(csv, columnDelimiter);
let keys = arrTable[1];
let types = arrTable[2];
for (let i = 4; i < arrTable.length; i++) {
let table = arrTable[i];
if(!table[1] || table[1] == '') continue;
obj[table[1]] = {ID: table[1]};
for (let j = 2; j < table.length; j++) {
if(!table[j] || table[j] == '') continue;
if(types[j] == 'int' || types[j] == 'float' || types[j] == 'double') obj[table[1]][keys[j]] = Number(table[j]);
else obj[table[1]][keys[j]] = table[j];
}
}
return obj;
},
csvToArray(csv, columnDelimiter = '\t') {
const table = csv.trim().replace(/\r\n?/g, '\n');
let quoteCounter = 0;
let lastDelimiterIndex = 0;
let arrTable = [[]];
let anchorRow = arrTable[arrTable.length - 1];
for (let i = 0; i < table.length; i++) {
const char = table[i];
if (char === '"' && table[i - 1] !== '\\') {
quoteCounter = quoteCounter ? 0 : 1;
if (quoteCounter) {
lastDelimiterIndex = i + 1;
}
} else if (
!quoteCounter &&
(char === columnDelimiter || char === '\n' || i === table.length - 1)
) {
const startPos = lastDelimiterIndex;
let col = startPos >= i ? '' : table.slice(startPos, i).trim();
if (col[col.length - 1] === '"') {
col = col.slice(0, col.length - 1);
}
anchorRow.push(col);
lastDelimiterIndex = i + 1;
if (char === '\n') {
anchorRow = arrTable[arrTable.push([]) - 1];
}
}
}
return arrTable;
},