我自己实现了一个对图片的引用计数,可以正常释放,但是当有新的prefab载入后通过引用载入之前被释放的图片时,该图片是一个不可用的对象:
贴一下我管理图片引用的代码:
let ngTextureCache = {};
let TextureRes = function(textureUrl, texture){
this.textureUrl = textureUrl;
this.texture = texture;
this.refCount = 1;
cc.log(‘new texture’, this.textureUrl, this.refCount);
};
TextureRes.prototype.retain = function(){
this.refCount++;
cc.log(‘retain texture’, this.textureUrl, this.refCount);
};
TextureRes.prototype.release = function(){
this.refCount–;
if(this.refCount == 0){
//cc.textureCache.removeTexture(this.texture);
this.texture.destroy();
//cc.textureCache.removeTextureForKey(this.textureUrl);
}
cc.log('release texture', this.textureUrl, this.refCount);
};
ngTextureCache.textures = {};
ngTextureCache.retainTexture = function (textureUrl, texture) {
let textureRes = ngTextureCache.textures[textureUrl];
if(textureRes!==undefined){
textureRes.retain();
} else {
textureRes = new TextureRes(textureUrl, texture);
ngTextureCache.textures[textureUrl] = textureRes;
}
};
ngTextureCache.releaseTexture = function (textureUrl) {
let textureRes = ngTextureCache.textures[textureUrl];
if(textureRes!==undefined){
textureRes.release();
if(textureRes.refCount==0){
delete ngTextureCache.textures[textureUrl];
}
}
};
ngTextureCache.retainTexturesForPrefab = function(prefabPath){
let deps = cc.loader.getDependsRecursively(prefabPath);
for (let i = 0; i < deps.length; ++i) {
let item = cc.loader.getRes(deps[i]);
if (item instanceof cc.Texture2D) {
if(item.url==’’){
cc.error(‘bad item’,item);
}
ngTextureCache.retainTexture(item.url, item);
}
}
};
ngTextureCache.releaseTexturesForPrefab = function(prefabPath){
let deps = cc.loader.getDependsRecursively(prefabPath);
for (let i = 0; i < deps.length; ++i) {
let item = cc.loader.getRes(deps[i]);
if (item instanceof cc.Texture2D) {
ngTextureCache.releaseTexture(item.url);
}
}
};