Nanfeng

Notes on software development, code, and curious ideas

Loading Remote Assets in Cocos Creator

Image URL with a file extension

1
2
3
4
5
6
7
8
const remoteUrl = "https://unknown.org/someres.png";
assetManager.loadRemote<ImageAsset>(remoteUrl, function (err, imageAsset) {
if (err) return;
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
});

Image URL without a file extension

When the URL does not include the image suffix, specify the remote file type explicitly:

1
2
3
4
5
6
7
8
const remoteUrl = "https://unknown.org/emoji?id=124982374";
assetManager.loadRemote<ImageAsset>(remoteUrl, { ext: '.png' }, function (err, imageAsset) {
if (err) return;
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
});

Load a file from an absolute device path

This can be used for a resource stored on the device, such as an image selected from the photo library:

1
2
3
4
5
6
7
8
const absolutePath = "/data/data/some/path/to/image.png";
assetManager.loadRemote<ImageAsset>(absolutePath, function (err, imageAsset) {
if (err) return;
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
});

Remote audio

1
2
3
4
5
const remoteUrl = "https://unknown.org/sound.mp3";
assetManager.loadRemote(remoteUrl, function (err, audioClip) {
if (err) return;
// Play the audio clip.
});

Remote text

1
2
3
4
5
const remoteUrl = "https://unknown.org/skill.txt";
assetManager.loadRemote(remoteUrl, function (err, textAsset) {
if (err) return;
// Use the loaded text.
});

Production code should handle errors, validate asset types, use HTTPS, and release resources when they are no longer needed.

+