You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
109 lines
3.1 KiB
109 lines
3.1 KiB
|
|
import { _decorator, Component, Node, Sprite, director, SpriteFrame, Asset, AssetManager, assetManager } from 'cc';
|
|
import { GEvent } from '../event/GEvent';
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('LangSprite')
|
|
export class LangSprite extends Component {
|
|
|
|
@property
|
|
path: string = "";
|
|
|
|
@property
|
|
key: string = "";
|
|
|
|
langSp: Sprite = null;
|
|
|
|
curentSpriteFrame: SpriteFrame = null;
|
|
|
|
onLoad() {
|
|
this.langSp = this.getComponent(Sprite);
|
|
}
|
|
|
|
onEnable() {
|
|
this.updateLang();
|
|
GEvent.Ins.on(GEvent.EVENT_LANG_CHANGE, this.updateLang, this);
|
|
}
|
|
|
|
onDisable() {
|
|
GEvent.Ins.off(GEvent.EVENT_LANG_CHANGE, this.updateLang, this);
|
|
if (this.curentSpriteFrame) {
|
|
this.curentSpriteFrame.decRef();
|
|
this.curentSpriteFrame = null;
|
|
}
|
|
}
|
|
|
|
async updateLang() {
|
|
try {
|
|
if (this.langSp == null || !this.node.isValid) return;
|
|
await gg.lang.whenReady();
|
|
let bundleName = 'lang_' + gg.lang.Current;
|
|
let path = this.path;
|
|
let key = this.key;
|
|
if (key == "") key = this.node.name;
|
|
key = key + "/spriteFrame";
|
|
let bundle = await this.loadBundle(bundleName);
|
|
if (!bundle) return;
|
|
let img = await this.loadRes(bundle, path + key, SpriteFrame) as SpriteFrame;
|
|
if (img) {
|
|
if (this.curentSpriteFrame && this.curentSpriteFrame != img) {
|
|
this.curentSpriteFrame.decRef();
|
|
}
|
|
if (this.curentSpriteFrame == img) return;
|
|
img.addRef();
|
|
this.curentSpriteFrame = img;
|
|
this.langSp.spriteFrame = img;
|
|
}
|
|
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
}
|
|
|
|
setKey(key: string) {
|
|
this.key = key;
|
|
this.updateLang();
|
|
}
|
|
|
|
setPath(path: string) {
|
|
this.path = path;
|
|
this.updateLang();
|
|
}
|
|
|
|
private async loadBundle(bundleName) {
|
|
return new Promise<AssetManager.Bundle>((resolve, reject) => {
|
|
let bundle = assetManager.getBundle(bundleName);
|
|
if (bundle) {
|
|
resolve(bundle);
|
|
return;
|
|
}
|
|
assetManager.loadBundle(bundleName, (err, bundle) => {
|
|
if (err) {
|
|
console.log(`加载Bundle:${bundleName}错误`, err);
|
|
resolve(null);
|
|
} else {
|
|
resolve(bundle);
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
private async loadRes(bundle: AssetManager.Bundle, assetPath, type = Asset) {
|
|
return new Promise<Asset>((resolve, reject) => {
|
|
let res = bundle.get(assetPath);
|
|
if (res) {
|
|
resolve(res);
|
|
return;
|
|
}
|
|
bundle.load(assetPath, type, (err, asset) => {
|
|
if (err) {
|
|
console.log(`加载Bundle:${bundle.name},path:${assetPath}资源错误`, err);
|
|
resolve(null);
|
|
} else {
|
|
resolve(asset);
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
|