i18n.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var _langCode = cc.sys.languageCode;
  2. // _langCode = 'en' //多国语言版本测试
  3. var _lang = _langCode;
  4. // cc.log('cc.sys.languageCode : ',_langCode);
  5. var _langHead = _langCode.substring(0,2);
  6. if(_langHead == 'zh'){
  7. if(_langCode == 'zh' || _langCode == 'zh-cn' || _langCode == 'zh-CN' ){
  8. _lang = 'zh-CN';
  9. }else{
  10. _lang = 'zh-HK';
  11. }
  12. }else{
  13. _lang = _langHead;
  14. }
  15. /**
  16. * 5国语言
  17. */
  18. const LANG_TYPE = cc.Enum({
  19. zh_CN : 'zh-CN',
  20. zh_HK : 'zh-HK',
  21. en : 'en',
  22. jo : 'jo',
  23. ko : 'ko'
  24. });
  25. const {ccclass, property} = cc._decorator;
  26. @ccclass
  27. export default class i18n extends cc.Component{
  28. public static data:any;
  29. onLoad(){
  30. cc.log('当前语言:'+_lang);
  31. }
  32. __init(callback:()=>void){
  33. //读取存档
  34. //读取语言文件包
  35. cc.resources.load('i18n/'+_lang, cc.JsonAsset, (err, jsonAsset:cc.JsonAsset) =>{
  36. if(err){
  37. cc.error(err);
  38. }else{
  39. i18n.data = jsonAsset.json;
  40. callback();
  41. }
  42. })
  43. }
  44. static t (key: string, opt?: any) {
  45. if(key.length > 50){
  46. return key
  47. }
  48. let str:string = i18n.data[key];
  49. // cc.log('key:',key)
  50. // cc.log('opt:',opt)
  51. if(!str){
  52. str = key;
  53. }
  54. // cc.log('str:',str)
  55. if(opt){//文字替换
  56. let keys = Object.keys(opt);
  57. for(let id in keys){
  58. let K = keys[id];
  59. let V = opt[K];
  60. str = str.replace('{'+K+'}',V);
  61. }
  62. }
  63. return str;
  64. }
  65. static lang(){
  66. return _lang
  67. }
  68. /*
  69. * 载入多国语言图片资源
  70. * @param path
  71. * @param callback
  72. */
  73. static load(path,callback:(sf:cc.SpriteFrame)=>void){
  74. cc.resources.load(path+'_'+_lang, cc.SpriteFrame, (err, sprintFrame:cc.SpriteFrame) =>{
  75. if(err){
  76. cc.error(err);
  77. }else{
  78. callback(sprintFrame);
  79. }
  80. })
  81. }
  82. }