# AssetRegistry

Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Asset

Source: https://github.com/playcanvas/engine/blob/dfcc50fbbfba2388843041a875ec0ef5d1a586c5/src/framework/asset/asset-registry.js#L45

Container for all assets that are available to this application. Note that PlayCanvas scripts
are provided with an AssetRegistry instance as `app.assets`.

## Constructors

### constructor

```ts
new AssetRegistry(loader: ResourceLoader)
```

Create an instance of an AssetRegistry.

**Parameters**

- `loader` ([`ResourceLoader`](https://api.playcanvas.com/engine/classes/ResourceLoader.md)): The ResourceLoader used to load the asset files.

## Properties

### bundles

```ts
bundles: BundleRegistry | null = null
```

BundleRegistry

### prefix

```ts
prefix: string | null = null
```

A URL prefix that will be added to all asset loading requests.

## Methods

### add

```ts
add(asset: Asset): void
```

Add an asset to the registry. If [Asset#preload](https://api.playcanvas.com/engine/classes/Asset.md#preload) is `true`, it will also get loaded.

**Parameters**

- `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)): The asset to add.

**Example**

```ts
const asset = new Asset("My Asset", "texture", {
    url: "../path/to/image.jpg"
});
app.assets.add(asset);
```

### filter

```ts
filter(callback: FilterAssetCallback): Asset[]
```

Return all Assets that satisfy a filter callback.

**Parameters**

- `callback` ([`FilterAssetCallback`](https://api.playcanvas.com/engine/types/FilterAssetCallback.md)): The callback function that is used to filter assets.
  Return `true` to include an asset in the returned array.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: A list of all Assets found.

**Example**

```ts
const assets = app.assets.filter(asset => asset.name.includes('monster'));
console.log(`Found ${assets.length} assets with a name containing 'monster'`);
```

### find

```ts
find(name: string, type?: string): Asset | null
```

Return the first Asset with the specified name and type found in the registry.

**Parameters**

- `name` (`string`): The name of the Asset to find.
- `type` (`string`, optional): The type of the Asset to find.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md) `| null`: A single Asset or null if no Asset is found.

**Example**

```ts
const asset = app.assets.find("myTextureAsset", "texture");
```

### findAll

```ts
findAll(name: string, type?: string): Asset[]
```

Return all Assets with the specified name and type found in the registry.

**Parameters**

- `name` (`string`): The name of the Assets to find.
- `type` (`string`, optional): The type of the Assets to find.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: A list of all Assets found.

**Example**

```ts
const assets = app.assets.findAll('brick', 'texture');
console.log(`Found ${assets.length} texture assets named 'brick'`);
```

### findByTag

```ts
findByTag(...query: any[]): Asset[]
```

Return all Assets that satisfy the search query. Query can be simply a string, or comma
separated strings, to have inclusive results of assets that match at least one query. A
query that consists of an array of tags can be used to match assets that have each tag of
array.

**Parameters**

- `query` (`any[]`): Name of a tag or array of tags.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: A list of all Assets matched query.

**Example**

```ts
const assets = app.assets.findByTag("level-1");
// returns all assets that tagged by `level-1`
```

**Example**

```ts
const assets = app.assets.findByTag("level-1", "level-2");
// returns all assets that tagged by `level-1` OR `level-2`
```

**Example**

```ts
const assets = app.assets.findByTag(["level-1", "monster"]);
// returns all assets that tagged by `level-1` AND `monster`
```

**Example**

```ts
const assets = app.assets.findByTag(["level-1", "monster"], ["level-2", "monster"]);
// returns all assets that tagged by (`level-1` AND `monster`) OR (`level-2` AND `monster`)
```

### get

```ts
get(id: number): Asset | undefined
```

Retrieve an asset from the registry by its id field.

**Parameters**

- `id` (`number`): The id of the asset to get.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md) `| undefined`: The asset.

**Example**

```ts
const asset = app.assets.get(100);
```

### getByUrl

```ts
getByUrl(url: string): Asset | undefined
```

Retrieve an asset from the registry by its file's URL field.

**Parameters**

- `url` (`string`): The url of the asset to get.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md) `| undefined`: The asset.

**Example**

```ts
const asset = app.assets.getByUrl("../path/to/image.jpg");
```

### list

```ts
list(filters?: object): Asset[]
```

Create a filtered list of assets from the registry.

**Parameters**

- `filters` (`object`, optional, default `{}`): Filter options.
    - `filters.preload` (`boolean`, optional): Filter by preload setting.

**Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: The filtered list of assets.

### load

```ts
load(asset: Asset, options?: object): void
```

Load the asset's file from a remote source. Listen for `load` events on the asset to find
out when it is loaded.

**Parameters**

- `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)): The asset to load.
- `options` (`object`, optional): Options for asset loading.
    - `options.bundlesFilter` ([`BundlesFilterCallback`](https://api.playcanvas.com/engine/types/BundlesFilterCallback.md), optional): A callback that will be called
      when loading an asset that is contained in any of the bundles. It provides an array of
      bundles and will ensure asset is loaded from bundle returned from a callback. By default,
      the smallest filesize bundle is chosen.
    - `options.bundlesIgnore` (`boolean`, optional): If set to true, then asset will not try to load
      from a bundle. Defaults to false.
    - `options.force` (`boolean`, optional): If set to true, then the check of asset being loaded or
      is already loaded is bypassed, which forces loading of asset regardless.

**Example**

```ts
// load some assets
const assetsToLoad = [
    app.assets.find("My Asset"),
    app.assets.find("Another Asset")
];
let count = 0;
assetsToLoad.forEach((assetToLoad) => {
    assetToLoad.ready((asset) => {
        count++;
        if (count === assetsToLoad.length) {
            // done
        }
    });
    app.assets.load(assetToLoad);
});
```

### loadFromUrl

```ts
loadFromUrl(url: string, type: string, callback: LoadAssetCallback): void
```

Use this to load and create an asset if you don't have assets created. Usually you would
only use this if you are not integrated with the PlayCanvas Editor.

**Parameters**

- `url` (`string`): The url to load.
- `type` (`string`): The type of asset to load.
- `callback` ([`LoadAssetCallback`](https://api.playcanvas.com/engine/types/LoadAssetCallback.md)): Function called when asset is loaded, passed (err,
  asset), where err is null if no errors were encountered.

**Example**

```ts
app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) {
    const texture = asset.resource;
});
```

### loadFromUrlAndFilename

```ts
loadFromUrlAndFilename(url: string, filename: string, type: string, callback: LoadAssetCallback): void
```

Use this to load and create an asset when both the URL and filename are required. For
example, use this function when loading BLOB assets, where the URL does not adequately
identify the file.

**Parameters**

- `url` (`string`): The url to load.
- `filename` (`string`): The filename of the asset to load.
- `type` (`string`): The type of asset to load.
- `callback` ([`LoadAssetCallback`](https://api.playcanvas.com/engine/types/LoadAssetCallback.md)): Function called when asset is loaded, passed (err,
  asset), where err is null if no errors were encountered.

**Example**

```ts
const file = magicallyObtainAFile();
app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) {
    const texture = asset.resource;
});
```

### remove

```ts
remove(asset: Asset): boolean
```

Remove an asset from the registry.

**Parameters**

- `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)): The asset to remove.

**Returns** `boolean`: True if the asset was successfully removed and false otherwise.

**Example**

```ts
const asset = app.assets.get(100);
app.assets.remove(asset);
```

## Events

### EVENT_ADD

```ts
static EVENT_ADD: string = 'add'
```

Fired when an asset is added to the registry. This event is available in three forms. They
are as follows:

1. `add` - Fired when any asset is added to the registry.
2. `add:[id]` - Fired when an asset is added to the registry, where `[id]` is the unique id
of the asset.
3. `add:url:[url]` - Fired when an asset is added to the registry and matches the URL
`[url]`, where `[url]` is the URL of the asset.

**Example**

```ts
app.assets.on('add', (asset) => {
   console.log(`Asset added: ${asset.name}`);
});
```

**Example**

```ts
const id = 123456;
app.assets.on('add:' + id, (asset) => {
   console.log(`Asset added: ${asset.name}`);
});
```

**Example**

```ts
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('add:url:' + asset.file.url, (asset) => {
   console.log(`Asset added: ${asset.name}`);
});
```

### EVENT_ERROR

```ts
static EVENT_ERROR: string = 'error'
```

Fired when an error occurs during asset loading. This event is available in two forms. They
are as follows:

1. `error` - Fired when any asset reports an error in loading.
2. `error:[id]` - Fired when an asset reports an error in loading, where `[id]` is the
unique id of the asset.

**Example**

```ts
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('error', (err, asset) => {
    console.error(err);
});
app.assets.load(asset);
```

**Example**

```ts
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('error:' + id, (err, asset) => {
    console.error(err);
});
app.assets.load(asset);
```

### EVENT_LOAD

```ts
static EVENT_LOAD: string = 'load'
```

Fired when an asset completes loading. This event is available in three forms. They are as
follows:

1. `load` - Fired when any asset finishes loading.
2. `load:[id]` - Fired when a specific asset has finished loading, where `[id]` is the
unique id of the asset.
3. `load:url:[url]` - Fired when an asset finishes loading whose URL matches `[url]`, where
`[url]` is the URL of the asset.

**Example**

```ts
app.assets.on('load', (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});
```

**Example**

```ts
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('load:' + id, (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});
app.assets.load(asset);
```

**Example**

```ts
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('load:url:' + asset.file.url, (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});
app.assets.load(asset);
```

### EVENT_REMOVE

```ts
static EVENT_REMOVE: string = 'remove'
```

Fired when an asset is removed from the registry. This event is available in three forms.
They are as follows:

1. `remove` - Fired when any asset is removed from the registry.
2. `remove:[id]` - Fired when an asset is removed from the registry, where `[id]` is the
unique id of the asset.
3. `remove:url:[url]` - Fired when an asset is removed from the registry and matches the
URL `[url]`, where `[url]` is the URL of the asset.

**Example**

```ts
app.assets.on('remove', (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});
```

**Example**

```ts
const id = 123456;
app.assets.on('remove:' + id, (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});
```

**Example**

```ts
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('remove:url:' + asset.file.url, (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});
```

## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md)

- `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler`
- `hasEvent(name: string): boolean`
- `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler`
- `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
- `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
