Options
All
  • Public
  • Public/Protected
  • All
Menu

Class CCLoader

Loader for resource loading process. The engine automatically initialize its singleton object {{loader}}.

Hierarchy

Index

Constructors

constructor

Properties

_assetTables

_assetTables: any

Private _autoReleaseSetting

_autoReleaseSetting: any

_cache

_cache: any = createMap(true)

Protected _pipes

_pipes: Array<IPipe>

Private _releasedAssetChecker_DEBUG

_releasedAssetChecker_DEBUG: any

assetLoader

assetLoader: AssetLoader

The asset loader in loader's pipeline, it's by default the first pipe.
It's used to identify an asset's type, and determine how to download it.

downloader

downloader: Downloader

The downloader in loader's pipeline, it's by default the second pipe.
It's used to download files with several handlers: pure text, image, script, audio, font, uuid.
You can add your own download function with addDownloadHandlers

getXMLHttpRequest

getXMLHttpRequest: Function

Gets a new XMLHttpRequest instance.

loader

loader: Loader

The loader in loader's pipeline, it's by default the third pipe.
It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid.
You can add your own download function with addLoadHandlers

md5Pipe

md5Pipe: null

The md5 pipe in loader's pipeline, it could be absent if the project isn't build with md5 option.
It's used to modify the url to the real downloadable url with md5 suffix.

onProgress

onProgress: Function | null

The default progression callback during the loading process, if no progression callback is passed to {{load}} function, then this default callback will be used.

Static ItemState

ItemState: any = ItemState

The item states of the LoadingItems, its value could be {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}}

Methods

getReferenceKey

  • getReferenceKey(assetOrUrlOrUuid: any): any

getResUuid

  • getResUuid(url: string, type?: Function, mount?: any, quiet?: any): string

Private loadResUuids

  • loadResUuids(uuids: any, progressCallback: any, completeCallback: any, urls?: any): void

Private parseLoadResArgs

  • parseLoadResArgs(type: any, onProgress: any, onComplete: any): { onComplete: any; onProgress: any; type: any }
  • Parameters

    • type: any
    • onProgress: any
    • onComplete: any

    Returns { onComplete: any; onProgress: any; type: any }

    • onComplete: any
    • onProgress: any
    • type: any

Private urlNotFound

  • urlNotFound(url: any, type: any, completeCallback: any): void

addDownloadHandlers

  • addDownloadHandlers(extMap: Map<string, Function>): void
  • Add custom supported types handler or modify existing type handler for download process.

    example
     loader.addDownloadHandlers({
         // This will match all url with `.scene` extension or all url with `scene` type
         'scene' : function (url, callback) {}
     });

    Parameters

    • extMap: Map<string, Function>

      Handlers for corresponding type in a map

    Returns void

addLoadHandlers

  • addLoadHandlers(extMap: Map<string, Function>): void
  • Add custom supported types handler or modify existing type handler for load process.

    example
     loader.addLoadHandlers({
         // This will match all url with `.scene` extension or all url with `scene` type
         'scene' : function (url, callback) {}
     });

    Parameters

    • extMap: Map<string, Function>

      Handlers for corresponding type in a map

    Returns void

appendPipe

  • appendPipe(pipe: IPipe): void

clear

  • clear(): void

copyItemStates

  • Copy the item states from one source item to all destination items.
    It's quite useful when a pipe generate new items from one source item,
    then you should flowIn these generated items into pipeline,
    but you probably want them to skip all pipes the source item already go through,
    you can achieve it with this API.

    For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again.

    Parameters

    • srcItem: IItem

      The source item

    • dstItems: IItem | Array<IItem>

      A single destination item or an array of destination items

    Returns void

flowIn

  • flowIn(items: Array<IItem>): void
  • Let new items flow into the pipeline.
    Each item can be a simple url string or an object, if it's an object, it must contain id property.
    You can specify its type by type property, by default, the type is the extension name in url.
    By adding a skips property including pipe ids, you can skip these pipe.
    The object can contain any supplementary property as you want.

    example
     pipeline.flowIn([
         'res/Background.png',
         {
             id: 'res/scene.json',
             type: 'scene',
             name: 'scene',
             skips: ['Downloader']
         }
     ]);

    Parameters

    • items: Array<IItem>

      The {{IItem}} to be appended to the current pipeline

    Returns void

flowInDeps

  • flowInDeps(owner: any, urlList: any, callback: any): IItem[]

flowOut

  • flowOut(item: IItem): void

getDependsRecursively

  • getDependsRecursively(owner: Asset | RawAsset | string): Array<string>
  • Get all resource dependencies of the requested asset in an array, including itself.
    The owner parameter accept the following types: 1. The asset itself; 2. The resource url; 3. The asset's uuid.
    The returned array stores the dependencies with their uuids, after retrieve dependencies,
    you can release them, access dependent assets by passing the uuid to getRes, or other stuffs you want.
    For release all dependencies of an asset, please refer to release Here is some examples:

    example
    import { loader, Texture2D } from 'cc';
    // Release all dependencies of a loaded prefab
    let deps = loader.getDependsRecursively(prefab);
    loader.release(deps);
    // Retrieve all dependent textures
    let deps = loader.getDependsRecursively('prefabs/sample');
    let textures = [];
    for (let i = 0; i < deps.length; ++i) {
        let item = loader.getRes(deps[i]);
        if (item instanceof Texture2D) {
            textures.push(item);
        }
    }

    Parameters

    • owner: Asset | RawAsset | string

      The asset itself or the asset url or the asset uuid

    Returns Array<string>

getItem

  • getItem(id: string): IItem | null

getRes

  • getRes<T>(url: string, type?: Function): T | null
  • Get resource data by id.
    When you load resources with load or loadRes, the url will be the unique identity of the resource. After loaded, you can acquire them by passing the url to this API.

    Type parameters

    • T

    Parameters

    • url: string

      The asset url, it should be related path without extension to the resources folder.

    • Optional type: Function

      If type is provided, the asset for correspond type will be returned

    Returns T | null

getResCount

  • getResCount(): Number

init

  • init(director: any): void

insertPipe

  • insertPipe(pipe: IPipe, index: number): void
  • Insert a new pipe at the given index of the pipeline.
    A pipe must contain an id in string and a handle function, the id must be unique in the pipeline.

    Parameters

    • pipe: IPipe

      The pipe to be inserted

    • index: number

      The index to insert

    Returns void

insertPipeAfter

  • insertPipeAfter(refPipe: IPipe, newPipe: IPipe): void

isAutoRelease

  • isAutoRelease(assetOrUrl: Asset | string): Boolean
  • Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.

    See: {{setAutoRelease}}, {{setAutoReleaseRecursively}}

    Parameters

    • assetOrUrl: Asset | string

      asset object or the raw asset's url

    Returns Boolean

load

  • load(resources: string | string[] | Object, progressCallback?: Function | null, completeCallback?: Function | null): void
  • Load resources with a progression callback and a complete callback.
    The progression callback is the same as Pipeline's LoadingItems.onProgress
    The complete callback is almost the same as Pipeline's LoadingItems.onComplete
    The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter.

    example
    import { loader, log, Texture2D } from 'cc';
    loader.load('a.png', function (err, tex) {
        log('Result should be a texture: ' + (tex instanceof Texture2D));
    });
    loader.load('http://example.com/a.png', function (err, tex) {
        log('Should load a texture from external url: ' + (tex instanceof Texture2D));
    });
    loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) {
        log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof Texture2D));
    });
    loader.load(['a.png', 'b.json'], function (errors, results) {
        if (errors) {
            for (let i = 0; i < errors.length; i++) {
                log('Error url [' + errors[i] + ']: ' + results.getError(errors[i]));
            }
        }
        let aTex = results.getContent('a.png');
        let bJsonObj = results.getContent('b.json');
    });

    Parameters

    • resources: string | string[] | Object

      Url list or load request list

    • Optional progressCallback: Function | null

      Progression callback

    • Optional completeCallback: Function | null

      Completion callback

    Returns void

loadRes

  • loadRes<T>(url: string, type: Constructor<T>, mount: string, progressCallback: LoadProgressCallback, completeCallback: LoadCompleteCallback<T>): any
  • loadRes<T>(url: string, type: Constructor<T>, progressCallback: LoadProgressCallback, completeCallback: LoadCompleteCallback<T>): any
  • loadRes<T>(url: string, type: Constructor<T>, completeCallback: LoadCompleteCallback<T>): any
  • Load assets from the "resources" folder inside the "assets" folder of your project.

    Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work.

    example
    import { loader, error, log, Prefab, SpriteFrame } from 'cc';
    // load the prefab (project/assets/resources/misc/character/cocos) from resources folder
    loader.loadRes('misc/character/cocos', function (err, prefab) {
        if (err) {
            error(err.message || err);
            return;
        }
        log('Result should be a prefab: ' + (prefab instanceof Prefab));
    });
    // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder
    loader.loadRes('imgs/cocos', SpriteFrame, function (err, spriteFrame) {
        if (err) {
            error(err.message || err);
            return;
        }
        log('Result should be a sprite frame: ' + (spriteFrame instanceof SpriteFrame));
    });

    Type parameters

    • T

    Parameters

    • url: string

      The url of the asset to be loaded, this url should be related path without file extension to the resources folder.

    • type: Constructor<T>

      If type is provided, only asset for correspond type will be loaded

    • mount: string
    • progressCallback: LoadProgressCallback

      Progression callback

    • completeCallback: LoadCompleteCallback<T>

      Completion callback

    Returns any

  • example
    import { loader, error, log, Prefab, SpriteFrame } from 'cc';
    // load the prefab (project/assets/resources/misc/character/cocos) from resources folder
    loader.loadRes('misc/character/cocos', function (err, prefab) {
        if (err) {
            error(err.message || err);
            return;
        }
        log('Result should be a prefab: ' + (prefab instanceof Prefab));
    });
    // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder
    loader.loadRes('imgs/cocos', SpriteFrame, function (err, spriteFrame) {
        if (err) {
            error(err.message || err);
            return;
        }
        log('Result should be a sprite frame: ' + (spriteFrame instanceof SpriteFrame));
    });

    Type parameters

    • T

    Parameters

    • url: string
    • type: Constructor<T>
    • progressCallback: LoadProgressCallback
    • completeCallback: LoadCompleteCallback<T>

    Returns any

  • example
    import { loader, error, log, Prefab, SpriteFrame } from 'cc';
    // load the prefab (project/assets/resources/misc/character/cocos) from resources folder
    loader.loadRes('misc/character/cocos', function (err, prefab) {
        if (err) {
            error(err.message || err);
            return;
        }
        log('Result should be a prefab: ' + (prefab instanceof Prefab));
    });
    // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder
    loader.loadRes('imgs/cocos', SpriteFrame, function (err, spriteFrame) {
        if (err) {
            error(err.message || err);
            return;
        }
        log('Result should be a sprite frame: ' + (spriteFrame instanceof SpriteFrame));
    });

    Type parameters

    • T

    Parameters

    • url: string
    • type: Constructor<T>
    • completeCallback: LoadCompleteCallback<T>

    Returns any

loadResArray

  • loadResArray(urls: string[], type?: Function, mount?: any, progressCallback?: Function, completeCallback?: Function): void
  • This method is like loadRes except that it accepts array of url.

    example
    import { loader, error, SpriteFrame } from 'cc';
    // load the SpriteFrames from resources folder
    let spriteFrames;
    let urls = ['misc/characters/character_01', 'misc/weapons/weapons_01'];
    loader.loadResArray(urls, SpriteFrame, function (err, assets) {
        if (err) {
            error(err);
            return;
        }
        spriteFrames = assets;
        // ...
    });

    Parameters

    • urls: string[]
    • Optional type: Function

      If type is provided, only assets for correspond type will be loaded

    • Optional mount: any
    • Optional progressCallback: Function

      Progression callback

    • Optional completeCallback: Function

      Completion callback

    Returns void

loadResDir

  • loadResDir(url: string, type?: Function, mount?: any, progressCallback?: Function, completeCallback?: Function): void
  • Load all assets in a folder inside the "assets/resources" folder of your project.

    Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work.

    example
    import { loader, error, Texture2D } from 'cc';
    // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame
    loader.loadResDir('imgs/cocos', function (err, assets) {
        if (err) {
            error(err);
            return;
        }
        let texture = assets[0];
        let spriteFrame = assets[1];
    });
    // load all textures in "resources/imgs/"
    loader.loadResDir('imgs', Texture2D, function (err, textures) {
        let texture1 = textures[0];
        let texture2 = textures[1];
    });
    // load all JSONs in "resources/data/"
    loader.loadResDir('data', function (err, objects, urls) {
        let data = objects[0];
        let url = urls[0];
    });

    Parameters

    • url: string

      The url of the directory to be loaded, this url should be related path to the resources folder.

    • Optional type: Function

      If type is provided, only assets for correspond type will be loaded

    • Optional mount: any
    • Optional progressCallback: Function

      Progression callback

    • Optional completeCallback: Function

      Completion callback

    Returns void

release

  • release(asset: Asset | RawAsset | string | Array<Asset | RawAsset | string>): void
  • Release the content of an asset or an array of assets by uuid.
    This method will not only remove the cache of the asset in loader, but also clean up its content.
    For example, if you release a texture, the texture asset and its gl texture data will be freed up.
    In complexe project, you can use this function with getDependsRecursively to free up memory in critical circumstances.
    Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors.
    If you only want to remove the cache of an asset, please use Pipeline.removeItem

    example
    // Release a texture which is no longer need
    loader.release(texture);
    // Release all dependencies of a loaded prefab
    let deps = loader.getDependsRecursively('prefabs/sample');
    loader.release(deps);
    // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up.
    // If you have some other nodes share a texture in this prefab, you can skip it in two ways:
    // 1. Forbid auto release a texture before release
    loader.setAutoRelease(texture2d, false);
    // 2. Remove it from the dependencies array
    let deps = loader.getDependsRecursively('prefabs/sample');
    let index = deps.indexOf(texture2d._uuid);
    if (index !== -1)
        deps.splice(index, 1);
    loader.release(deps);

    Parameters

    • asset: Asset | RawAsset | string | Array<Asset | RawAsset | string>

      Asset or assets to be released

    Returns void

releaseAll

  • releaseAll(): void

releaseAsset

  • releaseAsset(asset: Asset): void

releaseRes

  • releaseRes(url: string, type?: Function, mount?: any): void
  • Release the asset loaded by {{loadRes}}. Refer to {{release}} for detailed informations.

    Parameters

    • url: string

      The asset url, it should be related path without extension to the resources folder.

    • Optional type: Function

      If type is provided, the asset for correspond type will be returned

    • Optional mount: any

    Returns void

releaseResDir

  • releaseResDir(url: string, type?: Function, mount?: any): void
  • Release the all assets loaded by {{loadResDir}}. Refer to {{release}} for detailed informations.

    Parameters

    • url: string

      The url of the directory to release, it should be related path to the resources folder.

    • Optional type: Function

      If type is provided, the asset for correspond type will be returned

    • Optional mount: any

    Returns void

removeItem

  • removeItem(key: any): boolean

setAutoRelease

  • setAutoRelease(assetOrUrlOrUuid: Asset | string, autoRelease: Boolean): void
  • Indicates whether to release the asset when loading a new scene.
    By default, when loading a new scene, all assets in the previous scene will be released or preserved
    according to whether the previous scene checked the "Auto Release Assets" option.
    On the other hand, assets dynamically loaded by using loader.loadRes or loader.loadResDir
    will not be affected by that option, remain not released by default.
    Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.

    See: {{setAutoReleaseRecursively}}, {{isAutoRelease}}

    example
    // auto release the texture event if "Auto Release Assets" disabled in current scene
    loader.setAutoRelease(texture2d, true);
    // don't release the texture even if "Auto Release Assets" enabled in current scene
    loader.setAutoRelease(texture2d, false);
    // first parameter can be url
    loader.setAutoRelease(audioUrl, false);

    Parameters

    • assetOrUrlOrUuid: Asset | string

      The asset or its url or its uuid

    • autoRelease: Boolean

      Whether to release automatically during scene switch

    Returns void

setAutoReleaseRecursively

  • setAutoReleaseRecursively(assetOrUrlOrUuid: Asset | string, autoRelease: Boolean): void
  • Indicates whether to release the asset and its referenced other assets when loading a new scene.
    By default, when loading a new scene, all assets in the previous scene will be released or preserved
    according to whether the previous scene checked the "Auto Release Assets" option.
    On the other hand, assets dynamically loaded by using loader.loadRes or loader.loadResDir
    will not be affected by that option, remain not released by default.
    Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.

    See: {{setAutoRelease}}, {{isAutoRelease}}

    example
    // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene
    loader.setAutoReleaseRecursively(spriteFrame, true);
    // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene
    loader.setAutoReleaseRecursively(spriteFrame, false);
    // don't release the Prefab and all the referenced assets
    loader.setAutoReleaseRecursively(prefab, false);

    Parameters

    • assetOrUrlOrUuid: Asset | string

      The asset or its url or its uuid

    • autoRelease: Boolean

      Whether to release automatically during scene switch

    Returns void

Generated using TypeDoc