Obtaining and Loading assets

Cocos Creator uses the same asset management mechanism as Cocos Creator. In this section, we will introduce:

  • Declaration of asset attributes
  • How to set assets in the Inspector panel
  • Loading assets dynamically
  • Loading remote assets and device assets
  • Dependence and releasing assets

Declaration of asset attributes

In Cocos Creator, all types that inherit from Asset are collectively called assets, such asTexture2D, SpriteFrame,AnimationClip, Prefab, etc. Loading assets is unified and interdependent assets can be automatically preloaded.

For example: when the engine is loading the scene, it will automatically load the assets associated with the scene first. If these assets are associated with other assets, the other will be loaded first, and the scene loading will end after all loading is completed.

You can define an Asset property in the script like this:

  1. //test.ts
  2. import { _decorator, Component, Node, SpriteFrame } from "cc";
  3. const { ccclass, property } = _decorator;
  4. @ccclass("test")
  5. export class test extends Component {
  6. @property({type: SpriteFrame})
  7. private spriteFrame: SpriteFrame = null;
  8. }

How to set Assets in the Inspector panel

As long as the type is defined in the script, you can easily set the asset directly in the Inspector panel. Suppose, we create a script like this:

  1. //test.ts
  2. import { _decorator, Component, Node, SpriteFrame, Texture2D } from "cc";
  3. const { ccclass, property } = _decorator;
  4. @ccclass("test")
  5. export class test extends Component {
  6. @property({type: Texture2D})
  7. private texture: Texture2D = null;
  8. @property({type: SpriteFrame})
  9. private spriteFrame: SpriteFrame = null;
  10. }

After adding it to a node, it looks like this in the Inspector panel:

asset-in-properties-null

Next, we drag a Texture and a SpriteFrame from the Assets panel into the corresponding properties of the Inspector panel:

asset-in-properties-dnd

Resulting in:

asset-in-properties-dnd

This allows you to get and set assets directly within a script:

  1. start () {
  2. let spriteFrame = this.spriteFrame;
  3. let texture = this.texture;
  4. }

Although it is intuitive to set assets in the Attributes Inspector, the assets can only be set in the Scene, in advance. This means there is no way to switch assets dynamically. If you need to switch assets dynamically, take a look at this next section on Dynamic loading.

Dynamic loading

For dynamic loading, please refer to Dynamic Load Resources