可选参数

文:Santy-Wang,Xunyi

为了增加灵活性和可扩展性,Asset Manager 中大部分的加载接口包括 assetManager.loadAnyassetManager.preloadAny 都提供了 options 参数。options 除了可以配置 Creator 的内置参数,还可以自定义任意参数用于扩展引擎功能。如果开发者不需要配置引擎内置参数或者扩展引擎功能,可以无视它,直接使用更简单的 API 接口,比如 resources.load

目前 options 中引擎已使用的参数包括:

uuid, url, path, dir, scene, type, priority, preset, audioLoadMode, ext, bundle, onFileProgress, maxConcurrency, maxRequestsPerFrame, maxRetryCount, version, xhrResponseType, xhrWithCredentials, xhrMimeType, xhrTimeout, xhrHeader, reloadAsset, cacheAsset, cacheEnabled

注意:请 不要 使用以上字段作为自定义参数的名称,避免与引擎功能发生冲突。

扩展引擎

开发者可以通过在 管线自定义处理方法 中使用可选参数来扩展引擎的加载功能。

  1. // 扩展管线
  2. assetManager.pipeline.insert(function (task, done) {
  3. const input = task.input;
  4. for (let i = 0; i < input.length; i++) {
  5. if (input[i].options.myParam === 'important') {
  6. console.log(input[i].url);
  7. }
  8. }
  9. task.output = task.input;
  10. done();
  11. }, 1);
  12. assetManager.loadAny({'path': 'images/background'}, {'myParam': 'important'}, callback);
  13. // 注册处理方法
  14. assetManager.downloader.register('.myformat', function (url, options, callback) {
  15. // 下载对应资源
  16. const img = new Image();
  17. if (options.isCrossOrigin) {
  18. img.crossOrigin = 'anonymous';
  19. }
  20. img.onload = function () {
  21. callback(null, img);
  22. };
  23. img.onerror = function () {
  24. callback(new Error('download failed'), null);
  25. };
  26. img.src = url;
  27. });
  28. assetManager.parser.register('.myformat', function (file, options, callback) {
  29. // 解析下载完成的文件
  30. callback(null, file);
  31. });
  32. assetManager.loadAny({'url': 'http://example.com/myAsset.myformat'}, {isCrossOrigin: true}, callback);

通过可选参数,再结合管线和自定义处理方法,引擎可以获得极大的扩展度。Asset Bundle 可以看做是使用可选参数扩展的第一个实例。