Cocos Creator API

1.5.x

Cocos Creator is the game engine for the future.

loader static

Extends Pipeline
Module: cc
Parent Module: cc

Loader for resource loading process. It's a singleton object.

Properties

assetLoader Object

The asset loader in cc.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 Object

The downloader in cc.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

loader Object

The downloader in cc.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

There are no properties that match your current filter settings. You can change your filter settings in the index section on this page. index

Methods

addDownloadHandlers
(
  • extMap
)

Add custom supported types handler or modify existing type handler for download process.

name type description
extMap Object

Custom supported types with corresponded handler

examples:

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

addLoadHandlers
(
  • extMap
)

Add custom supported types handler or modify existing type handler for load process.

name type description
extMap Object

Custom supported types with corresponded handler

examples:

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

load
(
  • resources
  • [progressCallback ]
  • [completeCallback ]
)

Load resources with a progression callback and a complete callback. The progression callback is the same as Pipeline's onProgress The complete callback is almost the same as Pipeline's 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.

name type description
resources String | String[] | Object

Url list in an array

progressCallback optional Function

Callback invoked when progression change

  • completedCount Number

    The number of the items that are already completed

  • totalCount Number

    The total number of the items

  • item Object

    The latest item which flow out the pipeline

completeCallback optional Function

Callback invoked when all resources loaded

examples:

cc.loader.load('a.png', function (err, tex) {
    cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D));
});

cc.loader.load('http://example.com/a.png', function (err, tex) {
    cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D));
});

cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) {
    cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D));
});

cc.loader.load(['a.png', 'b.json'], function (errors, results) {
    if (errors) {
        for (var i = 0; i < errors.length; i++) {
            cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i]));
        }
    }
    var aTex = results.getContent('a.png');
    var bJsonObj = results.getContent('b.json');
});

loadRes
(
  • url
  • [type ]
  • [progressCallback ]
  • [completeCallback ]
)

Load resources 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.

name type description
url String

Url of the target resource. The url is relative to the "resources" folder, extensions must be omitted.

type optional Function

Only asset of type will be loaded if this argument is supplied.

progressCallback optional Function

Callback invoked when progression change.

  • completedCount Number

    The number of the items that are already completed.

  • totalCount Number

    The total number of the items.

  • item Object

    The latest item which flow out the pipeline.

completeCallback optional Function

Callback invoked when the resource loaded.

  • error Error

    The error info or null if loaded successfully.

  • resource Object

    The loaded resource if it can be found otherwise returns null.

examples:

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

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

loadResArray
(
  • urls
  • [type ]
  • [progressCallback ]
  • [completeCallback ]
)

This method is like loadRes except that it accepts array of url.

name type description
urls String[]

Array of URLs of the target resource. The url is relative to the "resources" folder, extensions must be omitted.

type optional Function

Only asset of type will be loaded if this argument is supplied.

progressCallback optional Function

Callback invoked when progression change.

  • completedCount Number

    The number of the items that are already completed.

  • totalCount Number

    The total number of the items.

  • item Object

    The latest item which flow out the pipeline.

completeCallback optional Function

A callback which is called when all assets have been loaded, or an error occurs.

  • error Error

    If one of the asset failed, the complete callback is immediately called with the error. If all assets are loaded successfully, error will be null.

  • assets Asset[] | Array

    An array of all loaded assets. If nothing to load, assets will be an empty array.

examples:

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

loadResDir
(
  • url
  • [type ]
  • [progressCallback ]
  • [completeCallback ]
)

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.

name type description
url String

Url of the target folder. The url is relative to the "resources" folder, extensions must be omitted.

type optional Function

Only asset of type will be loaded if this argument is supplied.

progressCallback optional Function

Callback invoked when progression change.

  • completedCount Number

    The number of the items that are already completed.

  • totalCount Number

    The total number of the items.

  • item Object

    The latest item which flow out the pipeline.

completeCallback optional Function

A callback which is called when all assets have been loaded, or an error occurs.

  • error Error

    If one of the asset failed, the complete callback is immediately called with the error. If all assets are loaded successfully, error will be null.

  • assets Asset[] | Array

    An array of all loaded assets. If nothing to load, assets will be an empty array.

  • urls String[]

    An array that lists all the URLs of loaded assets.

examples:

// load the texture (resources/imgs/cocos.png) and the corresponding sprite frame
cc.loader.loadResDir('imgs/cocos', function (err, assets) {
    if (err) {
        cc.error(err);
        return;
    }
    var texture = assets[0];
    var spriteFrame = assets[1];
});

// load all textures in "resources/imgs/"
cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) {
    var texture1 = textures[0];
    var texture2 = textures[1];
});

// load all JSONs in "resources/data/"
cc.loader.loadResDir('data', function (err, objects, urls) {
    var data = objects[0];
    var url = urls[0];
});

getRes
(
  • url
  • [type ]
)
Any

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.

name type description
url String
type optional Function

Only asset of type will be returned if this argument is supplied.

returns:

type: Any

getDependsRecursively
(
  • owner
)
Array

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:

name type description
owner Asset | RawAsset | String

The owner asset or the resource url or the asset's uuid

returns:

type: Array

examples:

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

release
(
  • asset
)

Release the content of an asset or an array of assets by uuid. Start from v1.3, 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:method

name type description
asset Asset | RawAsset | String | Array

examples:

// Release a texture which is no longer need
cc.loader.release(texture);
// Release all dependencies of a loaded prefab
var deps = cc.loader.getDependsRecursively('prefabs/sample');
cc.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
cc.loader.setAutoRelease(texture2d, false);
// 2. Remove it from the dependencies array
var deps = cc.loader.getDependsRecursively('prefabs/sample');
var index = deps.indexOf(texture2d._uuid);
if (index !== -1)
    deps.splice(index, 1);
cc.loader.release(deps);

releaseAsset
(
  • asset
)

Release the asset by its object. Refer to release for detailed informations.

name type description
asset Asset

releaseRes
(
  • url
  • [type ]
)

Release the asset loaded by loadRes. Refer to release for detailed informations.

name type description
url String
type optional Function

Only asset of type will be released if this argument is supplied.

releaseResDir
(
  • url
  • [type ]
)

Release the all assets loaded by loadResDir. Refer to release for detailed informations.

name type description
url String
type optional Function

Only asset of type will be released if this argument is supplied.

releaseAll ( )

Resource all assets. Refer to release for detailed informations.

setAutoRelease
(
  • assetOrUrlOrUuid
  • autoRelease
)

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 cc.loader.loadRes or cc.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: cc.loader.setAutoReleaseRecursively, cc.loader.isAutoRelease

name type description
assetOrUrlOrUuid Asset | String

asset object or the raw asset's url or uuid

autoRelease Boolean

indicates whether should release automatically

examples:

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

setAutoReleaseRecursively
(
  • assetOrUrlOrUuid
  • autoRelease
)

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 cc.loader.loadRes or cc.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: cc.loader.setAutoRelease, cc.loader.isAutoRelease

name type description
assetOrUrlOrUuid Asset | String

asset object or the raw asset's url or uuid

autoRelease Boolean

indicates whether should release automatically

examples:

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

isAutoRelease
(
  • assetOrUrl
)
Boolean

Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.

See: cc.loader.setAutoRelease, cc.loader.setAutoReleaseRecursively

name type description
assetOrUrl Asset | String

asset object or the raw asset's url

returns:

type: Boolean

constructor
(
  • pipes
)

Inherited from Pipeline:

Constructor, pass an array of pipes to construct a new Pipeline, the pipes will be chained in the given order.
A pipe is an object which must contain an id in string and a handle function, the id must be unique in the pipeline.
It can also include async property to identify whether it's an asynchronous process.

name type description
pipes Array

examples:

var pipeline = new Pipeline([
     {
         id: 'Downloader',
         handle: function (item, callback) {},
         async: true
     },
     {id: 'Parser', handle: function (item) {}, async: false}
 ]);

insertPipe
(
  • pipe
  • index
)

Inherited from Pipeline:

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.

name type description
pipe Object

The pipe to be inserted

index Number

The index to insert

appendPipe
(
  • pipe
)

Inherited from Pipeline:

Add a new pipe at the end of the pipeline.
A pipe must contain an id in string and a handle function, the id must be unique in the pipeline.

name type description
pipe Object

The pipe to be appended

flowIn
(
  • items
)

Inherited from Pipeline:

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.

name type description
items Array

examples:

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

flowInDeps
(
  • urlList
  • callback
)
Array deprecated

Inherited from Pipeline:

deprecated: since v1.3

Let new items flow into the pipeline and give a callback when the list of items are all completed.
This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
after all its dependencies are loaded, then you will need to use function to flow in all dependencies
found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback).

name type description
urlList Array
callback Function

returns:

type: Array

Items accepted by the pipeline

copyItemStates
(
  • srcItem
  • dstItems
)

Inherited from Pipeline:

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.

name type description
srcItem Object

The source item

dstItems Array | Object

A single destination item or an array of destination items

isFlowing ( ) Boolean deprecated

Inherited from Pipeline:

deprecated: since v1.3

Returns whether the pipeline is flowing (contains item) currently.

returns:

type: Boolean

getItems ( ) LoadingItems deprecated

Inherited from Pipeline:

deprecated: since v1.3

Returns all items in pipeline. Returns null, please use API of Loader or LoadingItems.

returns:

type: LoadingItems

getItem
(
  • id
)
Object

Inherited from Pipeline:

Returns an item in pipeline.

name type description
id Object

The id of the item

returns:

type: Object

removeItem
(
  • id
)
Boolean

Inherited from Pipeline:

Removes an completed item in pipeline. It will only remove the cache in the pipeline or loader, its dependencies won't be released. cc.loader provided another method to completely cleanup the resource and its dependencies, please refer to cc.loader.release

name type description
id Object

The id of the item

returns:

type: Boolean

succeed or not

clear ( )

Inherited from Pipeline:

Clear the current pipeline, this function will clean up the items.

There are no methods that match your current filter settings. You can change your filter settings in the index section on this page. index