# Asset

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

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L167

An Asset is the engine's record of a single resource: a texture, a material, a glTF container, a
sound, a script and so on. Assets live in the application's [AssetRegistry](https://api.playcanvas.com/engine/classes/AssetRegistry.md) at
[AppBase#assets](https://api.playcanvas.com/engine/classes/AppBase.md#assets), which loads them on demand.

An asset has five parts:

- `type` selects the [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) that loads it and the type of `resource`.
- `file` names the file that holds the data, when there is one.
- `data` carries JSON that either is the resource, as for materials, or describes how to process
the file, as for texture and model mappings.
- `options` carries handler-specific load options.
- `resource` holds the loaded object, such as a [Texture](https://api.playcanvas.com/engine/classes/Texture.md). `resources` holds every object
the handler produced when there is more than one, such as a cube map and its prefiltered levels.

Loading is driven by the registry: call [AssetRegistry#load](https://api.playcanvas.com/engine/classes/AssetRegistry.md#load), or set [preload](https://api.playcanvas.com/engine/classes/Asset.md#preload) so the
asset loads when added. Wait for the result with [ready](https://api.playcanvas.com/engine/classes/Asset.md#ready) or listen for the `load` and
`error` events. [unload](https://api.playcanvas.com/engine/classes/Asset.md#unload) releases the resource.

The `type` string also types the resource: `new Asset('brick', 'texture', file)` creates an
`Asset<'texture'>` whose `resource` is a [Texture](https://api.playcanvas.com/engine/classes/Texture.md) once loaded, and
`app.assets.find('brick', 'texture')` returns one. See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md) for the built-in types
and for adding application-defined ones. An asset whose type is only known as a `string` has a
`resource` of type `unknown`.

**Example**

```ts
const asset = new Asset('brick', 'texture', { url: 'textures/brick.png' });
app.assets.add(asset);
app.assets.load(asset);
asset.ready((asset) => {
    material.diffuseMap = asset.resource;
});
```

**template**

## Constructors

### constructor

```ts
new Asset<K extends string & {} | AssetType>(name: string, type: K, file?: object, data?: any, options?: object)
```

Create a new Asset record. Add it to the [AssetRegistry](https://api.playcanvas.com/engine/classes/AssetRegistry.md) with
[AssetRegistry#add](https://api.playcanvas.com/engine/classes/AssetRegistry.md#add) so the application can find and load it.

**Parameters**

- `name` (`string`): A non-unique but human-readable name which can be later used to
  retrieve the asset.
- `type` ([`K`](https://api.playcanvas.com/engine/classes/Asset.md#k)): The type of asset (an [AssetType](https://api.playcanvas.com/engine/types/AssetType.md)), which selects the resource
  handler and the type of [Asset#resource](https://api.playcanvas.com/engine/classes/Asset.md#resource). The types a developer commonly creates are:

  - "animation" - see [Animation](https://api.playcanvas.com/engine/classes/Animation.md) and [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md)
  - "animclip" - see [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md)
  - "animstategraph" - see [AnimStateGraph](https://api.playcanvas.com/engine/classes/AnimStateGraph.md)
  - "audio" - see [Sound](https://api.playcanvas.com/engine/classes/Sound.md)
  - "binary" - an `ArrayBuffer`
  - "container" - see [ContainerResource](https://api.playcanvas.com/engine/classes/ContainerResource.md)
  - "css" - a `string`
  - "cubemap" - see [Texture](https://api.playcanvas.com/engine/classes/Texture.md); null when only prefiltered levels are provided
  - "font" - see [Font](https://api.playcanvas.com/engine/classes/Font.md)
  - "gsplat" - a Gaussian splat resource
  - "html" - a `string`
  - "json" - the parsed JSON
  - "material" - see [Material](https://api.playcanvas.com/engine/classes/Material.md)
  - "model" - see [Model](https://api.playcanvas.com/engine/classes/Model.md)
  - "script" - see [Script](https://api.playcanvas.com/engine/classes/Script.md)
  - "shader" - a `string`
  - "sprite" - see [Sprite](https://api.playcanvas.com/engine/classes/Sprite.md)
  - "text" - a `string`
  - "texture" - see [Texture](https://api.playcanvas.com/engine/classes/Texture.md)
  - "textureatlas" - see [TextureAtlas](https://api.playcanvas.com/engine/classes/TextureAtlas.md)

  Types that the engine creates itself while loading, such as `render` or `scene`, are omitted
  here; every built-in type is listed in [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md). Any other string is accepted for an
  application-defined handler; see [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md) for typing its resource.
- `file` (`object`, optional): Details about the file the asset is made from. At the least must
  contain the 'url' field. For assets that don't contain file data use null.
    - `file.contents` (`ArrayBuffer`, optional): Optional file contents. This is faster than wrapping
      the data in a (base64 encoded) blob. Currently only used by container assets.
    - `file.filename` (`string`, optional): The filename of the resource file or null if no filename
      was set (e.g from using [AssetRegistry#loadFromUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurl)).
    - `file.hash` (`string`, optional): The MD5 hash of the resource file data and the Asset data
      field or null if hash was set (e.g from using [AssetRegistry#loadFromUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurl)).
    - `file.size` (`number`, optional): The size of the resource file or null if no size was set
      (e.g. from using [AssetRegistry#loadFromUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurl)).
    - `file.url` (`string`, optional): The URL of the resource file that contains the asset data.
- `data` (`any`, optional, default `{}`): JSON object or string with additional data about the asset.
  (e.g. for texture and model assets) or contains the asset data itself (e.g. in the case of
  materials).
- `options` (`object`, optional, default `{}`): The asset handler options. For container options see
  [ContainerHandler](https://api.playcanvas.com/engine/classes/ContainerHandler.md).
    - `options.crossOrigin` (`"anonymous" | "use-credentials" | null`, optional): For use with texture assets
      that are loaded using the browser. This setting overrides the default crossOrigin specifier.
      For more details on crossOrigin and its use, see
      https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin.

**Example**

```ts
// an Asset<'texture'>: once loaded, asset.resource is a Texture
const asset = new Asset("a texture", "texture", {
    url: "http://example.com/my/assets/here/texture.png"
});
```

## Properties

### id

```ts
id: number
```

The asset id.

### loaded

```ts
loaded: boolean = false
```

True if the asset has finished attempting to load the resource. It is not guaranteed
that the resources are available as there could have been a network error.

### loading

```ts
loading: boolean = false
```

True if the resource is currently being loaded.

### options

```ts
options: any = {}
```

Optional JSON data that contains the asset handler options.

### registry

```ts
registry: AssetRegistry | null = null
```

The asset registry that this Asset belongs to.

### tags

```ts
tags: Tags
```

Asset tags. Enables finding of assets by tags using the [AssetRegistry#findByTag](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findbytag) method.

### type

```ts
type: K
```

The type of the asset: one of the [AssetType](https://api.playcanvas.com/engine/types/AssetType.md) names, or the name of an
application-defined resource handler. See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md).

## Accessors

### data

```ts
get data(): any
set data(value: any)
```

Gets optional asset JSON data.

### file

```ts
get file(): any
set file(value: any)
```

Gets the file details or null if no file.

### name

```ts
get name(): string
set name(value: string)
```

Gets the asset name.

### preload

```ts
get preload(): boolean
set preload(value: boolean)
```

Gets whether to preload an asset.

### resource

```ts
get resource(): AssetResource<K> | undefined
set resource(value: AssetResource<K>)
```

Gets the asset resource. Its type follows the asset's type: a [Texture](https://api.playcanvas.com/engine/classes/Texture.md) for an
`Asset<'texture'>`, a [Material](https://api.playcanvas.com/engine/classes/Material.md) for an `Asset<'material'>` and so on (see
[AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md)), or `unknown` when the type is only known as a `string`. It is `undefined`
until the asset has loaded and after [Asset#unload](https://api.playcanvas.com/engine/classes/Asset.md#unload), so narrow it before use unless the
asset is known to be loaded, for example inside [Asset#ready](https://api.playcanvas.com/engine/classes/Asset.md#ready).

### resources

```ts
get resources(): AssetResource<K>[]
set resources(value: AssetResource<K>[])
```

Gets the asset resources. For a cube map asset, the first entry is the cube map and the
remaining entries are its prefiltered levels, some of which may be `null`.

## Methods

### getFileUrl

```ts
getFileUrl(): string | null
```

Return the URL required to fetch the file for this asset.

**Returns** `string | null`: The URL. Returns null if the asset has no associated file.

**Example**

```ts
const asset = app.assets.find("My Image", "texture");
const img = "&lt;img src='" + asset.getFileUrl() + "'&gt;";
```

### ready

```ts
ready(callback: AssetReadyCallback<K>, scope?: any): void
```

Take a callback which is called as soon as the asset is loaded. If the asset is already
loaded the callback is called straight away.

The callback fires on success only, and a failed load still marks the asset as loaded while
firing `error` rather than `load`. So a callback registered before the failure never runs,
and one registered after it runs immediately with [Asset#resource](https://api.playcanvas.com/engine/classes/Asset.md#resource) still null. Listen
for the `error` event as well whenever a failure has to be handled, check `asset.resource`
inside the callback, and never await this callback alone.

**Parameters**

- `callback` ([`AssetReadyCallback`](https://api.playcanvas.com/engine/types/AssetReadyCallback.md)`<`[`K`](https://api.playcanvas.com/engine/classes/Asset.md#k)`>`): The function called when the asset is ready. Passed
  the (asset) arguments.
- `scope` (`any`, optional): Scope object to use when calling the callback.

**Example**

```ts
const asset = app.assets.find("My Asset");
asset.ready((asset) => {
    // asset loaded
});
app.assets.load(asset);
```

### unload

```ts
unload(): void
```

Destroys the associated resource and marks asset as unloaded.
The `unload` event also fires while the asset is loading, allowing resource handlers to
cancel pending work.

**Example**

```ts
const asset = app.assets.find("My Asset");
asset.unload();
// asset.resource is null
```

## Events

### EVENT_ADDLOCALIZED

```ts
static EVENT_ADDLOCALIZED: string = 'add:localized'
```

Fired when we add a new localized asset id to the asset.

**Example**

```ts
asset.on('add:localized', (locale, assetId) => {
   console.log(`Asset ${asset.name} has added localized asset ${assetId} for locale ${locale}`);
});
```

### EVENT_CHANGE

```ts
static EVENT_CHANGE: string = 'change'
```

Fired when one of the asset properties `file`, `data`, `resource` or `resources` is changed.

**Example**

```ts
asset.on('change', (asset, property, newValue, oldValue) => {
   console.log(`Asset ${asset.name} has property ${property} changed from ${oldValue} to ${newValue}`);
});
```

### EVENT_ERROR

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

Fired if the asset encounters an error while loading.

**Example**

```ts
asset.on('error', (err, asset) => {
   console.error(`Error loading asset ${asset.name}: ${err}`);
});
```

### EVENT_LOAD

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

Fired when the asset has completed loading.

**Example**

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

### EVENT_PROGRESS

```ts
static EVENT_PROGRESS: string = 'progress'
```

Fired as the asset's file downloads, with the number of bytes received so far and the total
expected. Only asset types whose file is fetched as binary data report progress:
`animation` (GLB only), `audio`, `binary`, `container`, `gsplat`, `model` and `texture`.
Textures loaded through an image element have no download progress, so they fire once at 0
and once at a fixed placeholder total, whether or not the file was downloaded.

Please note:
- downloads are skipped when `asset.file.contents` is supplied, so no progress is reported
- totalBytes may not be reliable as it is based on the content-length header of the response

**Example**

```ts
asset.on('progress', (receivedBytes, totalBytes) => {
   console.log(`Asset ${asset.name} progress ${receivedBytes / totalBytes}`);
});
```

### EVENT_REMOVE

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

Fired when the asset is removed from the asset registry.

**Example**

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

### EVENT_REMOVELOCALIZED

```ts
static EVENT_REMOVELOCALIZED: string = 'remove:localized'
```

Fired when we remove a localized asset id from the asset.

**Example**

```ts
asset.on('remove:localized', (locale, assetId) => {
  console.log(`Asset ${asset.name} has removed localized asset ${assetId} for locale ${locale}`);
});
```

### EVENT_UNLOAD

```ts
static EVENT_UNLOAD: string = 'unload'
```

Fired just before the asset unloads the resource. This allows for the opportunity to prepare
for an asset that will be unloaded. E.g. Changing the texture of a model to a default before
the one it was using is unloaded.

**Example**

```ts
asset.on('unload', (asset) => {
   console.log(`Asset about to unload: ${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`
